Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Goal

The goal of this challenge is to write code that will execute once and only once. This means basically that it damages the program, script, or environment in some way. If rebooting the system allows the code to run again that is permitted.

Scoring

Number of votes. All assumptions must be clearly listed. Any answers just initiating a reboot or halt will be disqualified.

Additional Rules because Greg Hewgill is a demi-god

No root access is permitted.

End Date

The contest will close on May 31, 2014.

Edit

This contest has been changed to popularity contest.

share|improve this question
3  
possible duplicate of A program that deletes itself –  Peter Taylor May 28 at 7:04
6  
@PeterTaylor a possible Solution would be the a self delete but as the result are showing it isn't the only one. –  Templar May 28 at 7:21
46  
To a lot of people calling vi in a single terminal environment has this effect, no escape from it unless you reboot :) Just a joke here. –  orion May 28 at 20:41
4  
The site is free for you to propose such a question. –  ojblass May 30 at 22:40
3  
I suspect it will be closed as a duplicate. –  l0b0 Jun 1 at 7:52
show 11 more comments

49 Answers 49

up vote 269 down vote accepted

Vigil

Finally a usecase for Vigil!

def main():
  raise Exception()

Excerpt from the "language specification":

It goes without saying that any function that throws an exception which isn't caught is wrong and must be punished.

...

If an oath is broken, the offending function [...] will be duly punished.

How?

Simple: it will be deleted from your source code.

The only way to ensure your program meets its requirements to absolutely forbid code that fails to do so. With Vigil, it will do this for you automatically.

There are other ways to do this, because Vigil provides the keywords implore and swear which are basically oaths to adhere to certain pre- and post-conditions:

def main():
  swear 0 > 1
share|improve this answer
56  
No doubt, this deserves to win. –  Matteo Italia May 28 at 10:44
25  
Finally, a sufficiently vigilant language for the modern age! I'm going to start using it in production. All bugs must be purged. –  Claudiu May 28 at 15:55
6  
To me it seems that it is not necessarily the fault of the function that throws an uncaught exception, it could also be that the functions on the call stack are negligent for failing to catch it. It could even suggest the architecture of the whole application is flawed (Because perhaps there is no way to properly handle that exception without restructuring the code?) In short, the whole program should be deleted. –  Jonathan Pullano May 28 at 18:23
6  
@JonathanPullano you're not the first one to notice that ;) –  Martin Büttner May 28 at 18:24
11  
Additional points for swearing. A program making a confident false statement no doubt needs to be eliminated. –  orion May 28 at 20:49
show 6 more comments

Pretty much any Linux distro, 9 chars

This one is a classic!

#!/bin/rm

Put this in a file and run it:

> ed
a
#!/bin/rm
.
wq foo
> ls
Mail mbox foo
> chmod 777 foo
> ./foo
> ls
Mail mbox

Aaand it's gone!

As to what is going on: I'm really just running rm! #! is called a shebang. And if you put one of these followed by a path to some executable as the first line in your script, the program loader will execute your script file with whatever you wrote there - the default is usually #!/bin/bash or #!/bin/sh (Bourne-again shell / Bourne shell). The first argument passed to this script will be the filename itself (which is why you see so many solutions including %0 or $0 and the likes in here); so by making my file contain #!/bin/rm and running it, all I'm doing is passing the filename of my file to rm.

share|improve this answer
2  
Without ever having used Linux myself, I think it deletes the script file. –  Ourous May 28 at 11:23
21  
@NateKerkhofs the #! sequence starts a shebang, which identifies what interpreter you are going to use for the script - normally /bin/bash. Here, Flonk has used /bin/rm as an "interpreter". rm is a program which deletes files. because Linux thinks that we want rm to be an interpreter, it passes the filename as an argument to it. therefore, the file deletes itself –  professorfish May 28 at 11:27
7  
This is hysterical –  ojblass May 28 at 13:13
9  
@user80551 I don't need root access for this. –  Flonk May 28 at 13:38
5  
hmm... ./foo mbox –  Izkata May 28 at 16:06
show 11 more comments

x86 binary, 4 bytes

F0 0F C7 C8

Assumption: Must be run on a P5 Pentium CPU.

The above instruction is commonly known as the F00F bug. It attempts to execute an invalid instruction, prefixed with lock.

This freezes the CPU up completely (not a halt nor a reboot) and it doesn't even require root access.

share|improve this answer
3  
Wow... that is really interesting. –  ojblass May 28 at 4:55
    
Pulling the power cable and restarting won't fix it? –  Jack M May 28 at 18:35
11  
@JackM: It will, but that's explicitly allowed in the question. –  Dennis May 28 at 19:46
    
@Dennis Seems like a little bit of an edge case, since it doesn't really prevent the script from running, it stops anything from running. Still an interesting submission, though. –  Jack M May 28 at 20:11
7  
@JackM, that seems like a great way to stop the "script" from running. –  Paul Draper Jun 1 at 2:21
show 1 more comment

Bash, 5

>"$0"

Truncates itself to zero length.

If the filename doesn't contain spaces, >$0 works for 3 chars!

share|improve this answer
    
Actually, the quotes are never needed for a variable used in a redirect filename like this, even if the program or path to the program contains spaces, due to a special case in shell parsing rules. So you can always do it in 3 chars! –  apenwarr Jun 8 at 5:30
    
@apenwarr it says "$0: ambiguous redirect" when without quotes and the filename contains spaces –  professorfish Jun 8 at 6:34
add comment

Bash, 13 12

Not the shortest, but it doesn't actually delete the file or make the system unusable.

chmod 0 "$0"

If the filename doesn't contain spaces, you can remove the quotes to save 2 chars.

Explanation

It removes all permissions (rwx) from itself. When you attempt to run it, or even view its code, a second time, without manually restoring the permissions, it will say something like

bash: <FILENAME>: Permission denied

Restore the permissions with

chmod +rwx <FILENAME>

Old version

Only removes execute permissions, but one char longer (this was a question before it got changed to ):

chmod -x "$0"

Sneaky version by Łukasz Niemier

#!/bin/chmod 0
share|improve this answer
3  
chmod 0 works too –  gnibbler May 28 at 11:06
    
@gnibbler thnx, added –  professorfish May 28 at 11:09
    
I think you can call the program a and save yet 3 chars: chmod 0 a –  tohecz Jun 3 at 11:54
    
@tohecz that's basically cheating though –  professorfish Jun 3 at 12:48
3  
Even nicer #!/bin/chmod 0 –  Łukasz Niemier Jun 5 at 23:28
add comment

gzip

#!/bin/gzip

To much annoyance to people used to nondestructive commandline tools, gzip by default ruins the original file, replacing it with a gzipped version (adding a suffix).

This is a variation on the #!/bin/rm option, except this one is recoverable by manual human intervention (call gunzip on it). As a special bonus, the resulting file is much longer than the original (the difference depends on the filename length).

Warning: location of gzip may vary.

EDIT: as pointed out by WChargin, this is more portable:

#!/usr/bin/env gzip

The rest of the file can have any content. It's essentially a file that, when called, hides itself in a box and refuses to come out until you forcibly unpack it.

share|improve this answer
5  
I never thought of it before but you are absolutely correct. –  ojblass May 29 at 1:34
    
very interesting –  Grijesh Chauhan May 29 at 7:54
4  
"Warning: location of gzip may vary" — this isn't code-golf, so you can use #!/usr/bin/env gzip –  WChargin Jun 1 at 4:39
    
+1, very creative use of gzip –  Sarge Borsch Jun 6 at 22:21
add comment

Shell + sed, 16 bytes

Not quite as destructive as some of the other answers ;-)

This script inserts a comment # at the beginning of every line of itself:

sed -i s/^/#/ $0
share|improve this answer
add comment

Commodore 64 BASIC

This one doesn't delete the program.

1 POKE 2048,1

Self-destruct

According to the Commodore 64 memory map, address2048is unused, but it must contain a value of 0 so that the BASIC program can be RUN.

share|improve this answer
    
Does poke simply move a variable to a location? –  ojblass May 29 at 1:30
8  
@ojblass yes, effectively. poke a, b is equivalent to the C code *((unsigned char *)a) = b;. –  Jules May 29 at 5:54
    
I'd like to visualise my FaceBook pokes that way! –  Sunny R Gupta Jun 6 at 9:58
    
Oh wow... I remember PEEK and POKE from C64 BASIC! I was writing this stuff around 1977. –  Fixee Jul 5 at 19:34
add comment

6800 machine code - 1 byte

0xDD

This is known as HCF or Halt and Catch Fire

share|improve this answer
17  
Well, the rules say "Any answers just initiating a reboot or halt will be disqualified", but this doesn't just initiate a halt, because it also catches fire. Thus, +1! –  Trejkaz Jun 2 at 13:01
add comment

Assumption: Running Solaris, logged in as root

killall
share|improve this answer
    
does solaris really have such a thing? –  ojblass May 28 at 4:00
5  
Yes, it does just what it says on the tin and kills all running processes. –  Greg Hewgill May 28 at 4:01
    
one upvote for you! –  ojblass May 28 at 4:01
7  
1, The question mentions no root access is permitted. –  user80551 May 28 at 13:36
50  
@user80551 he's the reason for that rule. –  Seiyria May 28 at 14:58
show 5 more comments

Python, 18

open(__file__,'w')

Truncates the file by opening it in write-only mode.

share|improve this answer
11  
Just in case you're serious, it opens itself (__file__ refers to its own filename). Opening in w mode truncates the file, basically clears it. –  Bob May 29 at 17:50
    
@Bob I thought the file was only written when you .close()'d it. Thanks for the info! –  segfaultd May 29 at 22:38
4  
I think the truncation happens on the open, but regardless the Python runtime should flush all open files at the end of the program, and either Python or the OS will close them when the process ends. 'course, it's generally good practice to explicitly close open handles when you're done with them. –  Bob May 29 at 23:09
5  
The "right" way to handle files in Python is with... er, with. with open("myfile.txt","r") as thefile: and then your file-handling code will automatically close the file when you're done. –  Schilcote May 31 at 19:59
add comment

Batch: 5 Bytes

%0|%0

It is basically the forkbomb for Windows.

The app starts its first argument twice. Don't run it in a productive environment ;)

share|improve this answer
42  
Is there a productive windows environment? (I'm joking of course). –  orion May 28 at 20:25
9  
it looks so innocent! –  ojblass May 29 at 13:01
2  
Yeah it does, I actually got tricked once -.- –  Knerd May 29 at 17:34
6  
Ok, definitely don't try that. It didn't go well. –  Raphael_ Jun 3 at 15:14
13  
Don't have the rep to downvote, but it violates "runs only once" in the most severe way possible. –  Xan Jun 6 at 9:53
show 6 more comments

IBM's CMS Operating System, which is a single-user operating system which runs as a guest under IBM's VM Hypervisor, has an interesting file-structure.

Files consist of three elements, File Name, File Type, and File Mode. The File Mode consists of two elements, a single alphabetic, which for ease of explanation can be regarded in a similar way to the Drive Letter for Windows/MS-DOS, and a single numeric digit.

The single numeric digit has meaning, http://publib.boulder.ibm.com/infocenter/zvm/v5r4/index.jsp?topic=/com.ibm.zvm.v54.dmsa3/hcsd0b10127.htm, and for this task it is the number 3 which is interesting:

File Mode Number 3
File mode number 3 means that files are erased after they are read. You can use file mode number 3 if you do not want to maintain copies on your minidisks or in your SFS directories.

So, spend hours writing your script and file it as `LOST FOREVER A3'. Run it, it works first time. Set off home, job well done.

Note, no message is produced indicating the erasure. After all, everyone knows what that 3 means, don't they?

It is actually of course very useful. You can, once testing is complete, use the 3 for temporary files, and not have to clean up afterwards, because they are read-once files.

share|improve this answer
add comment

Commodore 64 BASIC

0 NEW

NEW deletes the program.

share|improve this answer
1  
What's that do? –  user973810 May 28 at 16:52
3  
@user973810 if i remember basic, new is for cleaning memory, so it will delete program –  user902383 May 28 at 17:08
2  
Nice. Not specific to Commodore 64, probably works as is on almost every 8-bit BASIC machine from the 80's... –  ysap Jun 5 at 22:56
    
You could OLD or O. it back too. I new'd 12 months of 12 year olds game coding genius ;p work by accident once. Then accidentally saved instead of old-ing. O. didnt work anymore :( I did learn how hex editors worked pretty sharpish though :) –  Matt Warren Jun 8 at 22:42
1  
@ysap: It would be more portable if it were using 1 as line number; not all BASIC implementations supported line number 0. –  celtschk Jun 22 at 14:38
add comment

JavaScript

localStorage.x = eval(localStorage.x + localStorage.x)

The first time you run it, it'll run fine:

>>> localStorage.x = eval(localStorage.x + localStorage.x)
NaN

If you try to run it more (even if you refresh), you'll get an error:

>>> localStorage.x = eval(localStorage.x + localStorage.x)
ReferenceError: NaNNaN is not defined
share|improve this answer
add comment

Bash , 12

Note: This is destructive.

:(){ :|:&};:

It's the popular bash fork-bomb. It exponentially eats all memory and PID's locking up the system. A hard-reboot will allow the code to be run again though why would you want to do that?


Bash , 10

:(){ :&};:

For two less chars, this eats your memory linearly.


Bash , 7

w;PATH=

w is chosen as the shortest executable that I could think of.

This simply erases the path variable so the shell can't find /usr/bin/w the next time. Restarting the shell fixes it as the path is usually stored in ~/.profile

share|improve this answer
    
Darn it :D I just had the same idea :P –  Knerd May 28 at 8:22
1  
:(){ :&};: shouldn't eat your memory. It stops as soon as it has forked, so there's only ever O(1) active. You've done while(fork());, what would eat your memory linearly is the equivalent of fork(); while(1);. –  marinus May 28 at 9:28
6  
Wow! those are some deadly emoticions! I best not call my computer bignosed frownyface :(){ .... –  steveverrill May 28 at 22:27
1  
If I remember correctly... the fork bomb periodically leaves one PID open. The script can be run again in that interval... and if that doesn't count, it is possible to kill all the forks with some effort. Rebooting is simply the easiest solution. –  Brilliand May 30 at 21:53
4  
I don't think this qualifies. It doesn't make it impossible for the script to run again, instead it guarantees that it runs again (many times). –  Ben Voigt May 31 at 19:45
show 4 more comments

C++ 71

The executable file "golf" is denied permission to run next time.

#include <stdlib.h>
int main()
{
system("chmod a-x golf");
return 0;
}

JavaScript/HTML 137, 145 with console test

<script id="s"> 
function h(){
console.log(1);
var s=document.getElementById("s");
h=s.innerHTML;
h=h.replace("h","g");
s.innerHTML=h;
}
share|improve this answer
10  
@Templar in the context of JavaScript, I think that refreshing the page counts as rebooting (maybe?) –  professorfish May 28 at 9:41
2  
Even if you weren't removing the script from the page, it would still only execute once. There's no point to this. –  nderscore May 28 at 13:06
2  
@nderscore Looks like the function h is what will only execute once. You have to actually call it from somewhere else (analogous to running a program, I guess). Say, <button onclick="h();">. –  Bob May 30 at 4:07
2  
Given that reloading the page is allowed, and your goal is only to prevent h from being executable more than once while it's already loaded, what's wrong with function h(){h=0}? –  Cory May 30 at 18:59
1  
@professorfish How do we attempt to "execute" <script id="s"> a second time? If refreshing the page counts as rebooting, then any javascript will meet the requirements of "executing only once per boot". –  nmclean Jun 4 at 17:35
show 6 more comments

C#

Shortest code for deleting self

Process.Start(new ProcessStartInfo("cmd.exe", "/C choice /C Y /N /D Y /T 3 & Del \"" + Assembly.GetExecutingAssembly().Location + "\""));

Code for making it unnoticeable in the UI

Process.Start( new ProcessStartInfo()
{
    Arguments = "/C choice /C Y /N /D Y /T 3 & Del \"" + Assembly.GetExecutingAssembly().Location+"\"",
    WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, FileName = "cmd.exe"
});
share|improve this answer
5  
At last, a C# answer! –  Pharap Jun 4 at 17:44
add comment

sh

#!/bin/sh
curl http://runonce.herokuapp.com/

Will run only once (and it shows "Hello, world!" if it runs), even if you reinstall the system, and put the script again.

share|improve this answer
    
I'd argue that this will run multiple times, it just produces no output after the first. –  Brilliand May 30 at 21:56
3  
That didn't even once show "Hello World" for me. –  Paŭlo Ebermann Jun 1 at 0:13
    
@PaŭloEbermann: Perhaps you browsed to the location in the code. Browsing counts as running the code. –  xfix Jun 1 at 8:12
    
What if I both reinstall the system and I also change my IP? –  Antonio Ragagnin Jun 1 at 13:00
    
@AntonioRagagnin: It will work again. It's not that I can reliably determine things when everything is different. –  xfix Jun 1 at 13:41
show 1 more comment

Ruby,14

It rewrites the source code as the name of the program.

IO.write $0,$0
share|improve this answer
1  
And what if the program is named "IO.write $0,$0"? "Assumption: Name the program something that isn't valid code in any language." –  Brilliand May 30 at 21:57
    
@Brilland a ruby program should always end with .rb and even if its name was "IO.write $0, $0#.rb" that won't work because when writing it will include the full path. –  Mhmd Jun 1 at 9:28
1  
@Mhmd a ruby program can end with anything. For example gem and irb are Ruby programs with no extension. –  bfontaine Jun 8 at 9:13
add comment

PHP, 22 20 chars

<?=unlink(__FILE__);

EDIT: Removed two chars at end per comments.

share|improve this answer
1  
This can be further simplified as: <?unlink(__FILE__);, the trailing ?> is not required –  leepowers Jun 8 at 3:54
    
You have to start with <?= or the start tag is not recognized. –  Michael Mior Jun 8 at 12:13
1  
PHP destroying itself...ha! E_NOTICE line 3048 –  metadings Jun 8 at 15:46
add comment

NodeJS - 33 bytes

require('fs').unlink(__filename);
share|improve this answer
    
Could you describe what this does for those who are unfamiliar with the language? –  Kyle Kanos May 30 at 17:38
1  
@KyleKanos It gets the filesystem module fs and the current filename __filename and removes that filename from the filesystem. –  Cory May 30 at 19:06
3  
You can elide the semicolon because they are optional in JavaScript. –  nalply Jun 1 at 12:07
add comment

Bash 9 8 Characters

nc -l 1&

Will only run once, because the port is blocked forever.

share|improve this answer
1  
I think this doesn't work, because 0 is a special port (it's reserved). When I run this on my computer I can open it multiple times. Also, it's a port < 1024, which means it requires root access to be listened on. –  heinrich5991 May 29 at 21:22
    
nc -l 1& would fix the problem with 0 and be one byte shorter, since the last space is not needed. –  kasperd Jun 1 at 14:59
    
@kasperd Thanks for the input :-) –  Falco Jun 2 at 7:40
    
@heinrich5991 ok - than I would need 11 chars without root access to use a Port like 9654 –  Falco Jun 2 at 7:41
    
Care to explain why you downvoted ? –  Falco Jun 22 at 22:57
add comment

Here's a couple. Unlike many, these are not destructive, just creative and unorthodox.

Bash

#!/usr/bin/env bash
read <<< ''
printf "$REPLY" > "$0"

This one's pretty simple. The variable $REPLY is created implicitly by read, but filled with an empty herestring. That empty string is then printf'ed into the current script. It is a rather obfuscated equivalent of the following:

#!/usr/bin/env bash
cat <<< '' > "$0" # probably a lot more portable

Windows Batch

copy con %0 < nul

The second one basically copies the console input, read from nul, into the current file.

share|improve this answer
    
Posted after this became a popularity contest –  impinball May 30 at 5:31
1  
The first one won't work without root permissions. Why are you trying to replace the null device? When run as root, this would actually make the system behave erratically. You are also overwriting the null while writing into it :) Why not just move it anywhere else? Such as mv "$0" "${0}x" or something? It should do the trick. –  orion May 30 at 9:14
    
Does the file still exist afterwards? –  impinball May 30 at 16:34
    
I now completely changed the Bash example. –  impinball May 30 at 18:03
    
How are these not destructive? –  ysap Jun 5 at 23:05
show 1 more comment

Batch, 5 bytes

Though I'd link to the many well documented fork bombs

The shortest seems to be in windows batch at 5 chars

%0|%0

However I will eschew fork bombs and simply offer a good old fashioned c++ memory leak

C++ 34 chars

int main(){for(;;)int *a=new int;}
share|improve this answer
5  
Either of these can clearly be run more than once. –  R.. May 28 at 13:47
1  
The more you run, the more you kill your machine. And you leak enough memory, you will starve your OS –  impinball May 30 at 5:39
1  
The C++ one will just throw an error when bad_alloc happens and everything is fine? –  Mikhail Jun 8 at 11:25
    
Huh. Why do people love the other fork bomb ones. Maybe it varies. tbh I only really use c# and I don't think you can murder your OS through the clr, but I thought you could wiyj batch, c++ etc. –  Nathan Cooper Jun 8 at 20:49
add comment

x86 Machine Code (5 bytes)

HEX:

EA0000FFFF

ASM:

JMP FFFF:0000

You can try with debug.exe:

C:\>debug
-a 100
0AE7:0100 jmp ffff:0000
0AE7:0105
-g=100

Explanation: BIOSis always at FFFF:0000 in memory. So this sequence boots the computer, if this is run in a protected command prompt in Windows it makes that process unresponsive.

share|improve this answer
    
Would you mind adding an explanation for those not that familiar with machine code? –  Martin Büttner Jun 2 at 9:44
add comment

Batch (6 characters)

This is assuming we have permission to delete the file, and of course can be done on Windows (maybe MS-DOS as well).

del %0
share|improve this answer
add comment

Bash (5)

rm $0

Assuming you don't have spaces in the filename.

share|improve this answer
1  
This is why Unix is better than Windows: rm instead of del saved you a byte. –  MadTux Jun 10 at 19:04
add comment

Bash: 4 chars

rm a

Put this in a file named a and run it on your Linux machine.

share|improve this answer
9  
rm * will work for every filename –  Antonio Ragagnin May 28 at 12:24
2  
@AntonioRagagnin It's better to stick to non-destructive scripts –  Daniel May 28 at 12:52
1  
rm $0 will also work for all filenames, at the cost of one character. –  fNek May 31 at 19:05
3  
@AntonioRagagnin So will rm -rf / --no-preserve-root, but better ;) –  Cole Johnson May 31 at 21:49
4  
@fNek No, it won't. Only for those without a whitespace in their name. –  glglgl May 31 at 21:57
show 1 more comment

Ruby, 15 14

Put this line to a file (del.rb):

File.delete $0

then run it (self-destructive) : ruby del.rb del.rb

share|improve this answer
1  
you can save 1 character by using :File.delete $0 –  Mhmd May 28 at 7:45
1  
@Mhmd oh right, thanks –  psal May 28 at 8:22
add comment

protected by Community Jun 7 at 17:12

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

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