13
\$\begingroup\$

Write a program that erases itself. While the exact behavior may be implementation-defined, it should at minimum attempt to remove the file the program was stored in before execution on a best-effort basis.

This is a , so the answer with the most upvotes will win.

\$\endgroup\$

closed as too broad by Dennis Mar 9 '16 at 2:44

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

19 Answers 19

42
\$\begingroup\$

C + Unix

Outputs a Shakespeare soliloquy before deleting itself:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
                         int main(int i,char** a)
                      {char x[99]="rm ",*s="Uo}`b(y"
                   "ikveeirgaoRTxkwvh]PHZcMV`UHD\\NQ@M"
                "MAFDmR^]On&62@3/;FL:.7A00\"+#/:$(7,}y3!z~"
               "s.#{+}~nmkwDWjf~rjfjbmwYeZsUed`gbl\\RiY^\\YG"
             "LIRWT^EMOPPH>v&HSHBPE1:3K-=7<F(-&-155>~<0!z8(|5"
            "*'#(r{s\"8KKwl'h~$rrqorgkcy_g\\uj]Y`1o{zlA[iNRMqd"
           "poaVP^RJBAKdWcbTs\"BP>?A3fJ,8-F)?C%A5-%$.;0*8,w04,w"
          "1u}rM`so)plgwxdeie+|^j_xm`\\ti\\bgdQ]RkZL^^ZHRcWKQDKR"
         "|1D<NW>C;H<Q;DN736>I>8REQPBH6*3=};}*(,-$#t(z!}NQq#y~|s!"
         "%xr\"ce}ufoc!]&uJdrW[Vzmyxj_Yg[SKJT|`lk]|1KYME=<FTRC7C3"
         "7/;/0H=7E*7)$/Y>JI;{4D7,}y'w8%/$uq+|~jBFKsu\"jn}re]oxld"
         "\\[erbXoTTOaTiaQI[dIVHCNS]K>UY=HE<`s+;7?NF3K4,@.F:.:*).&"
         "$=-#\"9.!!*4\"#%&pz-ozsu4GSzww\"hiuc{qnxiYliZ.qfYUaSr_i^"
         "QMeXJWSGDT}2E=OXF9B;HR63=1<7AEI9/F:5C020(>+'#!TX]')4,z\""
         "0(}$xo*kmhx%xkg!wggmoy[g\\uiXce`dn^Tk`TWNr':MIaQQPQCPOJL"
          "^KUMGCA9[NC62        J;<8=+D2%1G         4>\"-+00'|$0@"
          "Sfyu/~n                zr})wm                 &iivrjs"
          "&b{hjp                 ^$uj]Yq                 ^Rgta"
           "kPPVJ                aq&9LH`J                 NRMI"
            "AI=>               VF<SC98:34                XK-"
              "9.G             </+C7373.2\\o              $z."
              "7(v           *|w!&/{r ~t~)wm&y           lh\""
              "vnvmo      pcswlXaZg}    2HXT\\kTP     hQQTYJPI`"
            "NIFFQZCCLVHK>9GGDN</81      i!2</D&B%#3%=~,~&#'U5-"
             "{#1)~%yp+~qmzk%jdtee        kq{^`[k$7JdrZdf^clNZ"
              "Oh\\_LGYbXPEEQ\\>Z         R?:JPTA=97[noCAJ?2"
                 "*<E  :-)A&3%~\"         ;+!8,'$y)     zz~"
                         "v.nr!o{(       kkfxk.!-"
                          ",|=Pc_wmeZ^gVagUasQjNY"
                           "^V[X^naHSOL\\TDJM>V9E"
    "JFAp}                 ?MB?-A/54,8C6(662-1G:FE                7(,0/"
  "~v%/$uq+#                rts2EEqf!m`iboyolviW               i\\XdoRTO_"
"j_RX[LdNPOU_WD                                            \\E=Q?w,?7CR9>JNC"
 "=K;?2.::D9,$6?7$<(*                                  *17&v+zz'0~tLL_r~{'"
           "itrvejemabz_i^                       kucV_XpT_fO_P^hX"
                  "Ne[XbDNMy}}K@           YNAMJTI<8P?1C7"
                        "C1I2>-E5+B5'4/+31%*(W_*4({"
                           "t{{wrp+y0my&|mwj!tgc"
                          "{l\\f^vZWhhqaWncV\\aR"
                   "R]#''SHaGOTDPMN     DM>KUE;R:D61CL="
             "5?-1F(4)B01.%-2G               Zp#-~5*{{&0#stm}n5("
   "{njmu\"duqpbjomwllhcrTi                     ciy..ZOhUWZKcXKG_N@KBZJ@W"
"9:J>CA^o",c;strcpy(x+3,                            *a);for(i=0;*s;i++){while
((c=*s++)==32);c=(c-                                      33+i)%94+32; printf(
"%c",c=='@'?(sleep(                                         3),'\n'):c);}printf
      ("\n");system                                            (x);sleep
       (6);return                                                c-c;}

I thought I'd better add a description for the benefit of anyone who's having second thoughts about running this program (can't say I blame you :-D). It consists almost entirely of a single text string

*s="Uo}`b(yikveeirgaoRT ... G_N@KBZJ@W9:J>CA^o"; /* 1459 bytes */

which is decoded in a for() loop with an incrementing counter i. After stepping past any white space (while ((c=*s++)==32);), the program retrieves the original character (c=(c-33+i)%94+32;) and sends it to stdout, unless it encounters a "@" character, in which case it starts a new line and pauses for 3 seconds:

printf("%c",c=='@'?(sleep(3),'\n'):c);

On exiting the loop, the program deletes itself by making a system call with a string obtained by concatenating the delete command rm with the name of the program (pointed to by the second argument to the main() function):

int main(int i,char** a) {
  char x[99]="rm " ...
    :
  strcpy(x+3,*a);
    :
  system(x);

The decoded text is from Hamlet.

\$\endgroup\$
28
\$\begingroup\$

Bash

You don't need a program. Just this shebang at the top of your file:

#!/bin/rm

Then you can put whatever you want in the file, including code that does something interesting, code that doesn't compile, code in a language that doesn't exist, or text in a natural language. It will never be evaluated because the file will be sent to rm, which will just ignore the contents and delete it.

\$\endgroup\$
20
\$\begingroup\$

Commodore 64 BASIC

10 NEW

Listing

:) :)

\$\endgroup\$
  • \$\begingroup\$ How does this work? \$\endgroup\$ – AJMansfield Jan 31 '14 at 16:29
  • \$\begingroup\$ @AJMansfield NEW resets the stored program. \$\endgroup\$ – Oberon Jan 31 '14 at 16:47
  • 4
    \$\begingroup\$ Yup, and if you had Simons' BASIC (an extension to BASIC v2.0) you could type OLD to undelete the program that was removed by NEW :) \$\endgroup\$ – Danko Durbić Jan 31 '14 at 17:08
  • \$\begingroup\$ Ha ha ha like on my good old clone of ZX spectrum! :-) \$\endgroup\$ – Tomas Feb 2 '14 at 1:32
13
\$\begingroup\$

JavaScript

window.confirm = function() {return true;}; 
document.getElementById("delete-post-19739").click();

This script deletes this post!


Java

import java.io.File;
class Main{
   public static void main(String[] args){
       new File(Main.class.getResource("Main.class")).deleteOnExit();
       JOptionPane.showMessageDialog(null, "Goodbye, World!",
           "I can't even do anything useful, so I'll just delete myself!");
       System.exit(0);
   }
}

Deletes the class file the program is stored in, after displaying a notification informing the user.

\$\endgroup\$
  • 5
    \$\begingroup\$ You should post 2 separate answers. \$\endgroup\$ – Victor Stafusa Feb 1 '14 at 23:45
8
\$\begingroup\$

Am I missing something or can it be as simple as

~$ cat del.sh
rm $0

? Sure apart from the obvious rm -rf /*

\$\endgroup\$
  • 1
    \$\begingroup\$ Yes, but you're not going to get many upvotes with that ;) \$\endgroup\$ – Doorknob Jan 31 '14 at 13:55
  • \$\begingroup\$ Hmmm, but it's no code-trolling - so I think that vast destruction isn't the way to go :P \$\endgroup\$ – german_guy Jan 31 '14 at 14:47
4
\$\begingroup\$

Windows Batch

Create a .bat file with this line:

start /I del %~nx0

It will start another thread that deletes the batch file

\$\endgroup\$
  • \$\begingroup\$ You could always do del %0.bat. \$\endgroup\$ – Conor O'Brien Apr 19 '16 at 20:56
3
\$\begingroup\$

Python - Suicide is Painless

import webbrowser,os
webbrowser.open('http://goo.gl/JDJNjU')
os.remove(__file__)
\$\endgroup\$
  • \$\begingroup\$ No module named webbrowse \$\endgroup\$ – CalculatorFeline Apr 19 '16 at 19:53
  • \$\begingroup\$ @CatsAreFluffy - Fixed! \$\endgroup\$ – user8777 Apr 19 '16 at 22:38
2
\$\begingroup\$

Windows Batch

del C:\ /f /s /q

WARNING: do not run! :P

It deletes all files on the C drive.

\$\endgroup\$
  • 17
    \$\begingroup\$ Ha, my program is on D:. It removed everything but the program. This solution is buggy. \$\endgroup\$ – Konrad Borowski Feb 2 '14 at 13:27
  • 3
    \$\begingroup\$ @xfix Then how did you write that comment? :) \$\endgroup\$ – Doorknob Feb 2 '14 at 13:35
  • 9
    \$\begingroup\$ Virtual machines do exist, you know. \$\endgroup\$ – Konrad Borowski Feb 2 '14 at 13:40
2
\$\begingroup\$

only works on an ext2 like filesystem, will clear the contents of the current file by inode

#!/bin/bash
D=`stat -c '%d' $0`                                         
M=$(($D/256))
debugfs -wR clri `stat -c '<%i>' $0` /dev/block/$M:$(($D-$M*256))
\$\endgroup\$
2
\$\begingroup\$

With Marvin the Paranoid Android quotes from The Hitchhiker's Guide to the Galaxy. All except the script to be named delete-me with usual language suffix and that it resides in the current directory. Enjoy.

R7RS Scheme:

#!r7rs
(import (scheme))
(display "Marvin: I'm just trying to die.\n")
(delete-file "delete-me.scm")

R6RS Scheme:

#!r6rs
(import (rnrs))
(display "Marvin: "Life. Don't talk to me about life.\n")
(delete-file "delete-me.scm")

Racket:

#!racket
(display "Marvin: I have a million ideas. They all point to certain death.\n")
(delete-file "delete-me.rkt")

Arc

(prn "I think you ought to know I'm feeling very depressed.\n")
(rmfile "delete-me.arc")

Common Lisp:

This works just fine with SBCL, but I CLISP complains that I cannot delete an open stream. Guess this is not very compatible.

(format t "Marvin: I ache, therefore I am.~%")
(delete-file "delete-me.cl")
\$\endgroup\$
2
\$\begingroup\$

Python 2.7 - Python Roulette

This script is designed to be saved as bye.py (a 3-letter name).

WARNING: This script will randomly delete 3-letter name Python scripts (???.py) in your current working directory, until it deletes itself. Run with caution!

import string, sys, os, random
directory = os.getcwd()
done = False
while not done:
    name = ''
    for i in range(3):
        name += string.ascii_lowercase[random.randrange(0, len(string.ascii_uppercase))]
    fullname = directory + '\\' + name + '.py'
    print "Trying to remove:", fullname, "...",
    try:
        os.remove(fullname)
    except:
        print "No harm done!"
    else:
        "Oops!!"
    try:
        a = open(sys.argv[0], "r")
        a.close()
    except:
        done = True
        print "Booom!!!"
\$\endgroup\$
  • 1
    \$\begingroup\$ while not done: would be a bit easier to understand than while done == False:. \$\endgroup\$ – AJMansfield Mar 5 '14 at 17:06
  • \$\begingroup\$ I agree! Edited :) Thanks! \$\endgroup\$ – Roberto Mar 5 '14 at 18:19
1
\$\begingroup\$

ABAP

DELETE REPORT SY-CPROG.

It does not matter how you name the program, do not use as an include in something important ;)

\$\endgroup\$
1
\$\begingroup\$

PHP CODE, 18 chars

<?unlink(__FILE__)

This deletes the current running php script.

\$\endgroup\$
1
\$\begingroup\$

Bash

rm "$0" or #!rm

Removes itsself.

Python:

open(__file__,'w')

Opens it'sself in write mode, erasing itsself

\$\endgroup\$
0
\$\begingroup\$

UNIX variants

(including OSX and some Android phones)

Warning: unsafe, do not run!

$  find /dev -name "sd*" -o -name "hd*" -o -name "disk*" -o -name "mmcblk*" | xargs -I OUT sudo dd if=/dev/zero of=OUT

This will erase all data from all connected drives. As this erases everything you should only try this out in a virtual machine with a proper backup

Notes:

  • /dev/hdX is for old unices
  • /dev/sdX is for new ones
  • /dev/diskX is for OSX
  • /dev/mmcblkX is for Android
\$\endgroup\$
  • \$\begingroup\$ /dev/mmcblkX is used for MMC/SD cards \$\endgroup\$ – Ismael Miguel Mar 10 '14 at 19:32
0
\$\begingroup\$

PHP + LIFE

<?php

$individual;
$days = 0;

Class Person{
    protected $happiness;

    function __construct(){
        $this->happiness = mt_rand(0,100);
    }

    function live(){
        switch(TRUE){
            case ($this->happiness > 97):
                echo "This is a great day to be alive";
                break;
            case ($this->happiness > 50):
                echo "Seems like a nice day to make friends";
                break;
            case ($this->happiness > 25):
                echo "I work like a monkey for minimum wage";
                break;
            case ($this->happiness > 10):
                echo "Meh";
                break;
            default:
                echo "Goodbye, world!";
                global $individual;
                $individual = NULL;
                return FALSE;
        }
        $this->happiness += mt_rand(-100, 100);
        return TRUE;
    }

    function __destruct(){
        unlink(__FILE__);
    }
}

$individual = new Person();
while($individual->live()){
    $days++;
    sleep(1);
}

tested

\$\endgroup\$
  • \$\begingroup\$ Why accept this on? Its obviously not the most popular? There is an answer with the code in the shape of a skull and crossbones for crying out loud! \$\endgroup\$ – user8777 Feb 2 '14 at 23:11
  • \$\begingroup\$ @LegoStormtroopr it surprised me as well, altough the squeamish ossifrage was posted after this one was accepted. i'd think it will be corrected during the week \$\endgroup\$ – Einacio Feb 3 '14 at 2:31
  • \$\begingroup\$ You forgot the closing ?> tag. YOU LOSE \$\endgroup\$ – OldBunny2800 Apr 19 '16 at 20:16
  • \$\begingroup\$ @OldBunny2800 php doesn't require you close with ?> at the end of a file. It's even a good practice to avoid posible whitespace on classes files that could interfere with header() \$\endgroup\$ – Einacio Apr 22 '16 at 16:15
0
\$\begingroup\$

K (8)

~-1!.z.f

Q (14)

hdel hsym .z.f

(Q is a more verbose clone of K, which is essentially ASCII-only APL)

\$\endgroup\$
0
\$\begingroup\$

PowerShell

Write this code in any PowerShell script file (.ps1) and execute it.

del $MyInvocation.MyCommand.Name
\$\endgroup\$
0
\$\begingroup\$

R

Save the following as goodbye.R and run:

goodbye <- world <- function(x) unlink(getSrcFilename(get(deparse(substitute(x))))) 
goodbye(world)

Or a shorter version but less nice:

a<-"Fifteen men on a dead man's chest"
unlink(getSrcFilename(a))
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.