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.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top


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.


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.


This contest has been changed to popularity contest.

share|improve this question
@PeterTaylor a possible Solution would be the a self delete but as the result are showing it isn't the only one. – Lukei May 28 '14 at 7:21
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 '14 at 20:41
The site is free for you to propose such a question. – ojblass May 30 '14 at 22:40
echo "If you try to execute me again, it means you are an idiot."; <-- Nobody will execute more than once :P – Awal Garg Jun 5 '14 at 12:45
Would missile-related software have qualified? ;) – rsegal Jun 8 '14 at 4:28

57 Answers 57

up vote 383 down vote accepted


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.


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
No doubt, this deserves to win. – Matteo Italia May 28 '14 at 10:44
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 '14 at 15:55
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 '14 at 18:23
@JonathanPullano you're not the first one to notice that ;) – Martin Büttner May 28 '14 at 18:24
Additional points for swearing. A program making a confident false statement no doubt needs to be eliminated. – orion May 28 '14 at 20:49

Pretty much any Linux distro, 9 chars

This one is a classic!


Put this in a file and run it:

> ed
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
Without ever having used Linux myself, I think it deletes the script file. – Ourous May 28 '14 at 11:23
@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 '14 at 11:27
This is hysterical – ojblass May 28 '14 at 13:13
@user80551 I don't need root access for this. – Flonk May 28 '14 at 13:38
hmm... ./foo mbox – Izkata May 28 '14 at 16:06

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
Wow... that is really interesting. – ojblass May 28 '14 at 4:55
Pulling the power cable and restarting won't fix it? – Jack M May 28 '14 at 18:35
@JackM: It will, but that's explicitly allowed in the question. – Dennis May 28 '14 at 19:46
@JackM, that seems like a great way to stop the "script" from running. – Paul Draper Jun 1 '14 at 2:21
I remember when this bug was making the rounds. A kernelside workaround was found almost immediately -- it won't crash the computer unless you're running an OS without the patch. – zwol Jun 2 '14 at 2:28

Bash, 5


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 '14 at 5:30
@apenwarr it says "$0: ambiguous redirect" when without quotes and the filename contains spaces – professorfish Jun 8 '14 at 6:34
@apenwarr, it is needed if the shell that interprets that script is based on ksh88 or is bash not in posix mode. It's not about space, it's about any character of $IFS for bash and wildcard characters for bash and ksh88. A she-bang less script will usually be interpreted by the system's sh, but some shells including bash and ksh88 will interpret them in a child of themselves instead. – sch May 4 at 12:55



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
I never thought of it before but you are absolutely correct. – ojblass May 29 '14 at 1:34
very interesting – Grijesh Chauhan May 29 '14 at 7:54
"Warning: location of gzip may vary" — this isn't code-golf, so you can use #!/usr/bin/env gzip – wchargin Jun 1 '14 at 4:39
+1, very creative use of gzip – Sarge Borsch Jun 6 '14 at 22:21
+1 just for It's essentially a file that, when called, hides itself in a box and refuses to come out until you forcibly unpack it. You made my day, and it's 1am. – VoteToSpam Jul 22 '15 at 8:19

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.


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
chmod 0 works too – gnibbler May 28 '14 at 11:06
@gnibbler thnx, added – professorfish May 28 '14 at 11:09
I think you can call the program a and save yet 3 chars: chmod 0 a – yo' Jun 3 '14 at 11:54
@tohecz that's basically cheating though – professorfish Jun 3 '14 at 12:48
Even nicer #!/bin/chmod 0 – Łukasz Niemier Jun 5 '14 at 23:28

6800 machine code - 1 byte


This is known as HCF or Halt and Catch Fire

share|improve this answer
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 '14 at 13:01

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

Commodore 64 BASIC

This one doesn't delete the program.

1 POKE 2048,1


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 '14 at 1:30
@ojblass yes, effectively. poke a, b is equivalent to the C code *((unsigned char *)a) = b;. – Jules May 29 '14 at 5:54
I'd like to visualise my FaceBook pokes that way! – Sunny R Gupta Jun 6 '14 at 9:58
Oh wow... I remember PEEK and POKE from C64 BASIC! I was writing this stuff around 1977. – Fixee Jul 5 '14 at 19:34

Assumption: Running Solaris, logged in as root

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

Python, 18


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

share|improve this answer
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 '14 at 17:50
@Bob I thought the file was only written when you .close()'d it. Thanks for the info! – segfaultd May 29 '14 at 22:38
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 '14 at 23:09
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 '14 at 19:59
This could be shortened to something like open("","w"). – Ethan Bierlein Jun 18 '15 at 4:56

Batch: 5 Bytes


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
Is there a productive windows environment? (I'm joking of course). – orion May 28 '14 at 20:25
it looks so innocent! – ojblass May 29 '14 at 13:01
Ok, definitely don't try that. It didn't go well. – rmobis Jun 3 '14 at 15:14
Don't have the rep to downvote, but it violates "runs only once" in the most severe way possible. – Xan Jun 6 '14 at 9:53
I believe a human only executes it once and that it qualifies. – ojblass Jun 6 '14 at 12:17


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

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

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

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

Commodore 64 BASIC


NEW deletes the program.

share|improve this answer
What's that do? – user973810 May 28 '14 at 16:52
@user973810 if i remember basic, new is for cleaning memory, so it will delete program – user902383 May 28 '14 at 17:08
Nice. Not specific to Commodore 64, probably works as is on almost every 8-bit BASIC machine from the 80's... – ysap Jun 5 '14 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 '14 at 22:42
@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 '14 at 14:38

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,, 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

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 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 '14 at 8:22
:(){ :&};: 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 '14 at 9:28
Wow! those are some deadly emoticions! I best not call my computer bignosed frownyface :(){ .... – Level River St May 28 '14 at 22:27
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 '14 at 21:53
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 '14 at 19:45

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(){
var s=document.getElementById("s");
share|improve this answer
@Templar in the context of JavaScript, I think that refreshing the page counts as rebooting (maybe?) – professorfish May 28 '14 at 9:41
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 '14 at 13:06
@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 '14 at 4:07
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}? – Keen May 30 '14 at 18:59
With #include <sys/stat.h> you can access the chmod function directly, saving quite a few bytes (<stdlib.h> is no longer needed, and neither is system). Also, no return is needed. – Ben Voigt Jun 1 '14 at 5:50


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
At last, a C# answer! – Pharap Jun 4 '14 at 17:44
Why is choice required? – wizzwizz4 May 5 at 15:33



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

EDIT: I figured I would release a script behind runonce as well. Nothing special, as it wasn't supposed to be released either way, but whatever.

$db = pg_connect("[connection information]");

pg_query("DELETE FROM users WHERE time < now() - interval '1 day'");

$result = pg_query_params($db, "SELECT * FROM users WHERE ip = $1 LIMIT 1", array($ip));

if (!pg_fetch_row($result)) {
    echo "Hello, world!\n";
    pg_query_params($db, "INSERT INTO users (ip) VALUES ($1)", array($ip));

As well as database schema

    ip inet PRIMARY KEY,
    time timestamp with time zone NOT NULL DEFAULT now()
CREATE INDEX ON users (time);

The data is stored in Heroku's database, feel free to check their privacy policy if you like. I don't check the data stored in a database, it's stored purely to allow the code to execute once.

share|improve this answer
I'd argue that this will run multiple times, it just produces no output after the first. – Brilliand May 30 '14 at 21:56
That didn't even once show "Hello World" for me. – Paŭlo Ebermann Jun 1 '14 at 0:13
@PaŭloEbermann: Perhaps you browsed to the location in the code. Browsing counts as running the code. – xfix Jun 1 '14 at 8:12
@StéphaneGourichon: Yes, it remembers IPs, and there is no way to remove an IP before automatic removal. I decided to put the source code, so that you can check what it does. – xfix Jan 7 at 15:46
@StéphaneGourichon: pg_query_params pretty much protects from SQL injection. It won't be saved however, as '; DROP TABLE users;-- is not a valid IP (inet only accepts IPs), and therefore if you have a fake X-Forwarded-For header, your visit won't be saved. I don't consider it a problem myself. – xfix Jan 8 at 17:07

Bash (5)

rm $0

Assuming you don't have spaces in the filename.

share|improve this answer
This is why Unix is better than Windows: rm instead of del saved you a byte. – MadTux Jun 10 '14 at 19:04
@MadTux I prefer *nix to Unix. – wizzwizz4 May 5 at 15:36


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

IO.write $0,$0
share|improve this answer
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 '14 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 '14 at 9:28
@Mhmd a ruby program can end with anything. For example gem and irb are Ruby programs with no extension. – bfontaine Jun 8 '14 at 9:13
@bfontaine Which have shebangs. This doesn't. – wizzwizz4 May 5 at 15:37
@wizzwizz4 Shebangs have nothing to do with the extension. ruby foo and ruby foo.rb will work the same with or without a shebang. ./foo and ./foo.rb (assuming they’re executable) will both fail without shebang and succeed with it (assuming correct code, etc). – bfontaine May 6 at 7:52

PHP, 22 20 chars


EDIT: Removed two chars at end per comments.

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

My Name's Shell...PowerShell

Classic self destructing message:

Project X is a go

Meet Eagle 1 at WP Alpha

Further comms is hereby prohibited
This message will self destruct in 
5 seconds
5..1| %{$_;Sleep 1;}
rm $(.{$MyInvocation.ScriptName})
share|improve this answer

Bash 9 8 Characters

nc -l 1&

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

share|improve this answer
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 '14 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 '14 at 14:59
@kasperd Thanks for the input :-) – Falco Jun 2 '14 at 7:40
@heinrich5991 ok - than I would need 11 chars without root access to use a Port like 9654 – Falco Jun 2 '14 at 7:41
Care to explain why you downvoted ? – Falco Jun 22 '14 at 22:57

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

NodeJS - 33 bytes

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

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


#!/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 '14 at 5:31
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 '14 at 9:14
Does the file still exist afterwards? – impinball May 30 '14 at 16:34
I now completely changed the Bash example. – impinball May 30 '14 at 18:03
How are these not destructive? – ysap Jun 5 '14 at 23:05

Bash: 4 chars

rm a

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

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

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
you can save 1 character by using :File.delete $0 – Mhmd May 28 '14 at 7:45
@Mhmd oh right, thanks – psal May 28 '14 at 8:22

PHP - 23

share|improve this answer
I wonder if it is possible to drop the semicolon here. I know it's possible with short tags like this: <?= $var ?>. – nalply Jun 1 '14 at 12:09
@naiply: No. ?> implies semicolon (you can even get a syntax error mentioning ;), but end of document doesn't. – xfix Jun 1 '14 at 14:33

protected by Community Jun 7 '14 at 17:12

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, 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.