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. The goal is to do this in the fewest number of characters.

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
5  
@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
1  
Is it ok, if the programm shuts the PC down? –  Knerd May 28 at 8:54
    
No restarting the computer is equivalent to halt. –  ojblass May 28 at 13:10
7  
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
show 4 more comments

33 Answers

up vote 118 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
27  
No doubt, this deserves to win. –  Matteo Italia May 28 at 10:44
9  
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
3  
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
4  
@JonathanPullano you're not the first one to notice that ;) –  m.buettner May 28 at 18:24
4  
Additional points for swearing. A program making a confident false statement no doubt needs to be eliminated. –  orion May 28 at 20:49
show 1 more comment

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 at 4:55
    
Pulling the power cable and restarting won't fix it? –  Jack M May 28 at 18:35
2  
@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
    
@JackM, that seems like a great way to stop the "script" from running. –  Paul Draper 56 mins ago
add comment

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
9  
@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
3  
This is hysterical –  ojblass May 28 at 13:13
1  
@user80551 I don't need root access for this. –  Flonk May 28 at 13:38
3  
hmm... ./foo mbox –  Izkata May 28 at 16:06
show 6 more comments

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"
share|improve this answer
2  
chmod 0 works too –  gnibbler May 28 at 11:06
    
@gnibbler thnx, added –  professorfish May 28 at 11:09
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

Bash, 5

>"$0"

Truncates itself to zero length.

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

share|improve this answer
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.

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
2  
I never thought of it before but you are absolutely correct. –  ojblass May 29 at 1:34
    
very interesting –  Grijesh Chauhan 2 days ago
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
1  
@ojblass yes, effectively. poke a, b is equivalent to the C code *((unsigned char *)a) = b;. –  Jules 2 days ago
add comment

6800 machine code - 1 byte

0xDD

This is known as HCF or Halt and Catch Fire

share|improve this answer
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
1  
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
3  
1, The question mentions no root access is permitted. –  user80551 May 28 at 13:36
23  
@user80551 he's the reason for that rule. –  Seiyria May 28 at 14:58
show 3 more comments

Batch: 5 Bytes

%0|%0

It is basically the forbomb for Windows.

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

share|improve this answer
6  
Is there a productive windows environment? (I'm joking of course). –  orion May 28 at 20:25
    
it looks so innocent! –  ojblass 2 days ago
    
Yeah it does, I actually got tricked once -.- –  Knerd 2 days ago
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
    
:(){ :&};: 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
1  
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 yesterday
2  
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 7 hours ago
show 2 more comments

Python, 18

open(__file__,'w')

I really don't know why this works.

share|improve this answer
2  
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 2 days ago
    
@Bob I thought the file was only written when you .close()'d it. Thanks for the info! –  segfaultd 2 days ago
2  
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 2 days ago
1  
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 7 hours ago
add comment

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

0NEW
share|improve this answer
1  
What's that do? –  user973810 May 28 at 16:52
2  
@user973810 if i remember basic, new is for cleaning memory, so it will delete program –  user902383 May 28 at 17:08
add comment

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
    
Can't I just refresh the page and rerun the code? –  Templar May 28 at 7:15
9  
@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 yesterday
1  
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 yesterday
show 2 more comments

Bash 9 Characters

nc -l 0 &

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 2 days ago
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
add 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
    
@Mhmd oh right, thanks –  psal May 28 at 8:22
add 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
4  
Either of these can clearly be run more than once. –  R.. May 28 at 13:47
    
The more you run, the more you kill your machine. And you leak enough memory, you will starve your OS –  impinball yesterday
add comment

Ruby,14

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 yesterday
add comment

PHP - 23

<?=fopen(__FILE__,'w');
share|improve this answer
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
4  
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
    
rm $0 will also work for all filenames, at the cost of one character. –  fNek 8 hours ago
    
@AntonioRagagnin So will rm -rf / --no-preserve-root, but better ;) –  Cole Johnson 5 hours ago
    
@fNek No, it won't. Only for those without a whitespace in their name. –  glglgl 5 hours ago
add comment

Python 24

Name the file 'q'

import os
os.remove("q")
share|improve this answer
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 yesterday
    
That didn't even once show "Hello World" for me. –  Paŭlo Ebermann 3 hours ago
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 yesterday
    
@KyleKanos It gets the filesystem module fs and the current filename __filename and removes that filename from the filesystem. –  Cory yesterday
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 yesterday
    
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 yesterday
    
Does the file still exist afterwards? –  impinball yesterday
    
I now completely changed the Bash example. –  impinball yesterday
add comment

Haskell - 80 bytes

Pre base-4.6.0.0 : May not work on Windows. This depends on how the program is invoked.

import System.Environment
import System.Directory
main=getProgName>>=removeFile

Post base-4.6.0.0 : A bit longer but always works.

import System.Environment
import System.Directory
main=getExecutablePath>>=removeFile
share|improve this answer
    
It's now a popularity contest. –  impinball yesterday
add comment

PHP, 22 chars

<?=unlink(__FILE__);?>
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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