A program that deletes itself

22

6

If a compiled language is used, the program must delete the compiled executable (but need not delete the source file). If an interpreted language is used, the program must delete the source file.

My opening bid:

Python (29 characters)

import os;os.remove(__file__)

Edit: to prevent solutions like rm -rf /, the program must not delete anything except the executable or source file.

html,body{margin:0;padding:0;height:100%;overflow:hidden}
 <iframe src="https://xmikee1.github.io/ppcg-leaderboard/?id=19355" width="100%" height="100%" style="border:none;">Oops, your browser is too old to view this content! Please upgrade to a newer version of your browser that supports HTML5.</iframe>

EMBLEM

Posted 2014-01-25T03:23:59.077

Reputation: 2 179

You might as well use a newline instead of a semicolon for the python answer. It's the same number of bytes and it's more readable. – Esolanging Fruit – 2017-05-07T11:40:00.883

May the submission be a function or does it have to be a full program? – FlipTack – 2017-12-04T20:26:55.310

possible duplicate of Write a program that deletes itself

– John Dvorak – 2014-01-25T03:39:04.467

2@JanDvorak That question was stricter, requiring a .exe file. This is more lax. – EMBLEM – 2014-01-25T03:39:50.113

Hmm... what if I vote to close in the opposite direction, then? – John Dvorak – 2014-01-25T03:41:14.370

@JanDvorak That would be excellent! And a first, an old question closed in favour of a newer one. – EMBLEM – 2014-01-25T03:41:55.873

Vote cast. Now let's wait and see :-) – John Dvorak – 2014-01-25T03:43:52.387

3code-golf, not [tag:popularity-contest]? Aww. – Justin – 2014-01-25T04:19:08.820

10@Quincunx I don't believe in popularity contests. Real code is not first validated on its elegance, but its correctness. – EMBLEM – 2014-01-25T04:24:27.913

Obviously relevant: http://youtu.be/Z86V_ICUCD4

– Adam Maras – 2014-01-25T07:37:56.270

@JanDvorak Okay, so prefer the trivial question where interpreted languages can do it with no problem. – Cruncher – 2014-01-27T14:23:49.923

@EMBLEM I think you may be on the wrong forum. Also, I disagree that this is a duplicate. The linked problem specifically asks for a windows executable, which is a different problem statement entirely.

– primo – 2014-01-31T11:17:17.180

you have to actually delete the file, truncating it doesn't count? – None – 2014-05-29T13:28:02.697

Answers

21

Bash script (7 characters, 7 bytes)

rm "$0"

anthony.c

Posted 2014-01-25T03:23:59.077

Reputation: 224

@bacchusbeale just tested on Linux Mint 17.2 64-bit and it deleted itself correctly, whether called directly à la ./scriptname, or called like bash scriptname. How did you get it to try to delete /bin/bash ? – Stéphane Gourichon – 2016-01-04T19:50:16.867

1@StéphaneGourichon Probably 'cause he's running rm "$0" in the Bash shell instead of in a batch script. You should edit the header like so: # Bash script, 7 bytes – MD XF – 2017-05-30T16:33:10.847

@MDXF I see a variant : rm "$0" yields rm: cannot remove 'bash': No such file or directory. – Stéphane Gourichon – 2017-05-31T04:36:56.340

1Doesn't work if the script file name contains spaces. – user80551 – 2014-01-25T03:46:16.023

Good eye! I've updated the script to work with files with spaces in them. Only adds two more characters. Thanks! – anthony.c – 2014-01-25T03:50:08.840

Does this work if the file name contains double quotes? – John Dvorak – 2014-01-25T07:28:11.487

1@JanDvorak: Yes. By execution that would be e.g. ./the\"program, ./'the"program', './tha"program'. All works as intended. (Quotes needs to be escaped or enclosed in single quotes on call.) Would also work on files containing names with newline etc. – Runium – 2014-01-26T04:37:21.270

Bad luck with the quotation marks, gave my answer the 1 byte edge. – unclemeat – 2014-01-31T10:53:05.197

This tries to remove /bin/bash which is denied! – bacchusbeale – 2014-05-28T19:55:38.937

15

Unix? (9):

#!/bin/rm

A classic. Uses rm as interpreter, for instant self-deletion. Not the very shortest though.

ɐɔıʇǝɥʇuʎs

Posted 2014-01-25T03:23:59.077

Reputation: 4 449

1The #! line isn't counted in score. – Pavel – 2017-05-07T03:10:24.167

@Phoenix: It is if it's unusual for the language you're using; only completely standard #! lines that just give the name of the language's default interpreter count as zero. This is a very unusual #! line as far as Bash goes. (Not that this actually works in Bash, although there are other languages where it works.) – None – 2017-06-16T06:06:16.120

1This isn't actually a Bash program (if you run it explicitly using bash, it won't delete anything). It's a UNIX/Linux executable. (It also works in Perl, which emulates UNIX/Linux's handling of #! lines so that it can be used to run shellscripts on platforms that can't do it natively.) – None – 2017-06-16T06:06:54.437

@Pavel Hmm... 0 bytes? – ɐɔıʇǝɥʇuʎs – 2017-09-11T11:46:13.340

5Or if you want to be cheaty: a 0-byte rm program. – nyuszika7h – 2014-07-02T18:07:39.087

10

Batch - 6 bytes

Del %0

Pretty simple. Note: Works even if the name contains spaces.

unclemeat

Posted 2014-01-25T03:23:59.077

Reputation: 2 302

doesn't work if invoked without the suffix, though - "test" as opposed to "test.bat" – peter ferrie – 2017-11-27T21:44:08.520

Only if the file name doesn't have spaces. – Isiah Meadows – 2014-05-30T04:38:10.063

@impinball, Sorry? – unclemeat – 2014-05-30T04:59:50.177

Just pointing out a little bug. If you specify DOS, it isn't, but it'll break pretty easily in Windows (ex. in Program Files). No apologies needed. – Isiah Meadows – 2014-05-30T05:26:09.793

My bad...it's okay. I misremembered that quotes aren't needed in this case because they are automatically included in this. – Isiah Meadows – 2014-05-30T05:28:42.563

All good. Adding tilde removes surrounding quotes. %~0. – unclemeat – 2014-05-30T05:32:43.780

I know. That's what I realized after I commented. – Isiah Meadows – 2014-05-30T05:57:12.423

9

Ruby, 14 characters

File.delete $0

$0 is a special global variable that contains the name of the currently running script.

Doorknob

Posted 2014-01-25T03:23:59.077

Reputation: 68 138

I'm pretty sure you can drop the space. – Darren Stone – 2014-01-25T08:26:29.150

This is why I made my version of the question much more strict. Interpreted languages can do it with no problem. The idea is that a natively running application can't just pull the rug out from underneath itself – Cruncher – 2014-01-27T14:22:49.043

6

BASIC-80 / BASICA / GW-BASIC / IBM BASIC / Commodore 64 BASIC / Vintage BASIC / Commodore LCD BASIC / Atari BASIC *

5 bytes

1 NEW

Well, that's about as simple as it gets. NEW creates a new program, so putting this anywhere in your program will delete it.

Proof of concept on IBM BASIC (putting NEW on line 40 for clarity):

* Yeah, I listed every old BASIC version I've tested this in (or pretty much ever used)

MD XF

Posted 2014-01-25T03:23:59.077

Reputation: 11 605

2+1, There is something rather poetic about this. Existential even. – Wossname – 2017-05-30T20:27:01.473

5

PHP, 17 characters

unlink(__FILE__);

Tobias Mädel

Posted 2014-01-25T03:23:59.077

Reputation: 179

4This PHP program prints unlink(__FILE__);. It does not delete the file. – rightfold – 2017-05-08T23:06:25.127

6I'm not sure why anyone would downvote this; it's perfectly valid. You may want to include an open tag, though <?unlink(__FILE__); – primo – 2014-01-31T10:53:06.190

1@rightfold it works as described if you include an opening tag, which I would have assumed to add – Darren H – 2019-08-01T10:01:57.860

3

PowerShell (32)

del $MyInvocation.MyCommand.Name

microbian

Posted 2014-01-25T03:23:59.077

Reputation: 2 297

3

Perl 5 (8 characters)

unlink$0

$0 is the script name, and unlink removes it. Normally, you'd at least add a space in between for readability.

Joachim Isaksson

Posted 2014-01-25T03:23:59.077

Reputation: 1 161

3

C# (112)

Process.Start("cmd.exe","/C choice /C Y /N /D Y /T 3 & Del " + Application.ExecutablePath);
Application.Exit();

Shamelessly stolen from http://www.codeproject.com/Articles/31454/How-To-Make-Your-Application-Delete-Itself-Immedia

microbian

Posted 2014-01-25T03:23:59.077

Reputation: 2 297

3

k (8)

~-1!.z.f

Or the q equivalent for 14:

hdel hsym .z.f

skeevey

Posted 2014-01-25T03:23:59.077

Reputation: 4 139

3

Python, 18

open(__file__,'w')

Opens itsself in write-only mode, erasing itself.

NoOneIsHere

Posted 2014-01-25T03:23:59.077

Reputation: 1 916

9This truncates the file. It does not delete it. – rightfold – 2017-05-08T23:07:23.763

2

R, 26 characters

unlink(sys.frame(1)$ofile)

plannapus

Posted 2014-01-25T03:23:59.077

Reputation: 8 610

1

JavaScript (ES6), 13 bytes

f=_=>delete f

Try It

Logs the source of f, calls f (which deletes f), tries to log f again but throws an error because f is now undefined.

f=_=>delete f
console.log(f)
f()
console.log(f)

Shaggy

Posted 2014-01-25T03:23:59.077

Reputation: 24 623

1

Nodejs, 32 bytes

require("fs").unlink(__filename)

user69105

Posted 2014-01-25T03:23:59.077

Reputation:

1

JS, 37 bytes

document.documentElement.innerHTML=""

Does this count? It kills javascript on the page

sobored

Posted 2014-01-25T03:23:59.077

Reputation: 11

You don't need the spaces around the = – programmer5000 – 2017-05-10T13:23:56.153

1

tcl, 18

file delete $argv0

demoATTENTION: It is only a one time demo! Only the first time it will be runnable. Please reserve it to the question's original poster. To try: press the Execute button. The green area will not report any error. After that, any subsequent clicks on the Execute button will result on a not found error!

sergiol

Posted 2014-01-25T03:23:59.077

Reputation: 3 055

1

Node.js - 22 chars

fs.unlink(__filename);

Tobias Mädel

Posted 2014-01-25T03:23:59.077

Reputation: 179

1

Julia, 13 bytes

rm(@__FILE__)

Simple. But longer. :P

Rɪᴋᴇʀ

Posted 2014-01-25T03:23:59.077

Reputation: 7 410

1

Vitsy + bash, 8 bytes

iG' mr',

iG       Get the name of the use declaration at the top item (-1) (returns the current one)
  ' mr'  Concatenate "rm " to the front of it.
       , Execute via shell.

Addison Crump

Posted 2014-01-25T03:23:59.077

Reputation: 10 763

1

Mathematica, 29 bytes

DeleteFile@NotebookFileName[]

A Simmons

Posted 2014-01-25T03:23:59.077

Reputation: 4 005

1

C, 32 bytes

main(c,v)char**v;{remove(v[0]);}

Josh

Posted 2014-01-25T03:23:59.077

Reputation: 2 783

1Missing }s are allowed in C? Wow! – CalculatorFeline – 2017-06-25T14:57:12.213

Nope, just a typo! My character count included the closing } but I apparently copy/pasted the snippet incorrectly. Thanks for pointing it out! – Josh – 2017-06-27T15:59:55.440

Well, since the anonymous downvoter doesn't feel like leaving a comment or retracting their vote, I have deleted my answer, which I based off of yours. You can golf this down to 29 bytes: main(c,v)int**v;{remove(*v);} – MD XF – 2017-07-22T19:46:53.403

@MDXF I am not sure if changing char** to int** is technically valid. I'm worried about potential alignment issues. – Josh – 2017-07-25T17:42:18.383

1@Josh Well; it works... so I don't see why not. Code golf is all about using horrible methods that aren't technically valid. – MD XF – 2017-07-25T17:42:50.577

1

Lua, 17 bytes

os.remove(arg[0])

This actually only works if you run the program by typing out the full filepath, i.e.
lua ~/Scripts/removeself.lua would work, but lua removeself.lua would not, assuming a filename of removeself.lua and a current working directory of ~/Scripts.

As far as I know, there's no way to find the actual filepath of a script, just the arguments passed to it. I do know about debug.getinfo(1).source, but in my testing that game exactly the same results as arg[0]. If anyone knows of a way to find the filepath, please let me know.

Jesse Paroz

Posted 2014-01-25T03:23:59.077

Reputation: 31

0

VBA, 69 67 Bytes

Subroutine that takes no input and deletes itself.

Requires that the code below be the first line in the active code pane, and that VBA has trusted access to the VBE Project model.

Sub a:Application.VBE.CodePanes(1).CodeModule.DeleteLines 1:End Sub

-2 bytes for replacing ActiveCodePane with with CodePane(1)

Taylor Scott

Posted 2014-01-25T03:23:59.077

Reputation: 6 709

0

T-SQL, 28 bytes

CREATE PROC d AS DROP PROC d

It just drops/removes the procedure and the code when executing itself. Usage:

EXECUTE d

WORNG ALL

Posted 2014-01-25T03:23:59.077

Reputation: 61

0

shortC, 10 bytes

Aremove(*@

How it works:

A           main function
 remove(    delete file specified in next string
        *@  program name

Equivalent C program:

int main(int argc, char **argv){remove(*argv);}

MD XF

Posted 2014-01-25T03:23:59.077

Reputation: 11 605

0

8086/8088 machine code, 1 byte

aa    stosb

Assumptions:

  • The registers CS, IP, ES, DI, and AL are all initially 0.
  • This code is placed at address 0.

The stosb instruction stores the byte in the AL register at the memory location pointed to by ES and DI, then increments or decrements DI. In this case, it stores the byte 0 at the memory address 0, which happens to be where the instruction itself is.

Granted, this program doesn't delete a file or anything. But if you manage to get your hands on an 8086 processor, poke this program into memory, and run it, it will in fact overwrite itself.

Tanner Swett

Posted 2014-01-25T03:23:59.077

Reputation: 531

0

PowerShell v3 - 17

ri $PSCommandPath

Rynant

Posted 2014-01-25T03:23:59.077

Reputation: 2 353

0

Julia - 25 bytes

Write this into a file, and then include the file with include("<filename here>") and run f():

f()=rm(functionloc(f)[1])

This is, obviously, a function - I'm not sure how one would go about detecting the file name of a file being run directly (as an include statement without a function definition in it).

Glen O

Posted 2014-01-25T03:23:59.077

Reputation: 2 548

0

C++, 137 bytes.

Works most of the time on windows

#include <stdlib.h> 
#include <string>
int main(int, char*v[]){char c[99];sprintf(c,"start cmd /C del \"%s\"/Q", *v);return system(c);}

C, 90 bytes

void main(int n,char**v){char c[99];sprintf(c,"start cmd /C del \"%s\"/Q", *v);system(c);} 

Johan du Toit

Posted 2014-01-25T03:23:59.077

Reputation: 1 524

Most of the time? – Addison Crump – 2016-03-04T08:27:04.387

1You could save a lot of bytes by removing the unused #include <string>, removing extraneous spaces, and making this C, which lets you remove the int and return. Additionally, you need #include <stdio.h> to make this work, since that's where sprintf is declared. – Mego – 2016-03-04T08:29:04.457

0

MATLAB, 36 bytes

delete([mfilename('fullpath'),'.m'])

Save the above code as an m-file following Matlab's filename guidelines.

slvrbld

Posted 2014-01-25T03:23:59.077

Reputation: 619