247
\$\begingroup\$

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.

\$\endgroup\$
17
  • 8
    \$\begingroup\$ possible duplicate of A program that deletes itself \$\endgroup\$ May 28, 2014 at 7:04
  • 7
    \$\begingroup\$ @PeterTaylor a possible Solution would be the a self delete but as the result are showing it isn't the only one. \$\endgroup\$
    – Lukei
    May 28, 2014 at 7:21
  • 116
    \$\begingroup\$ 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. \$\endgroup\$
    – orion
    May 28, 2014 at 20:41
  • 21
    \$\begingroup\$ echo "If you try to execute me again, it means you are an idiot."; <-- Nobody will execute more than once :P \$\endgroup\$ Jun 5, 2014 at 12:45
  • 33
    \$\begingroup\$ Would missile-related software have qualified? ;) \$\endgroup\$
    – rsegal
    Jun 8, 2014 at 4:28

81 Answers 81

540
\$\begingroup\$

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
\$\endgroup\$
11
  • 122
    \$\begingroup\$ No doubt, this deserves to win. \$\endgroup\$ May 28, 2014 at 10:44
  • 85
    \$\begingroup\$ Finally, a sufficiently vigilant language for the modern age! I'm going to start using it in production. All bugs must be purged. \$\endgroup\$
    – Claudiu
    May 28, 2014 at 15:55
  • 14
    \$\begingroup\$ 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. \$\endgroup\$ May 28, 2014 at 18:23
  • 11
    \$\begingroup\$ @JonathanPullano you're not the first one to notice that ;) \$\endgroup\$ May 28, 2014 at 18:24
  • 36
    \$\begingroup\$ Additional points for swearing. A program making a confident false statement no doubt needs to be eliminated. \$\endgroup\$
    – orion
    May 28, 2014 at 20:49
309
\$\begingroup\$

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.

\$\endgroup\$
22
  • 12
    \$\begingroup\$ Without ever having used Linux myself, I think it deletes the script file. \$\endgroup\$
    – Οurous
    May 28, 2014 at 11:23
  • 64
    \$\begingroup\$ @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 \$\endgroup\$
    – user16402
    May 28, 2014 at 11:27
  • 20
    \$\begingroup\$ This is hysterical \$\endgroup\$
    – ojblass
    May 28, 2014 at 13:13
  • 27
    \$\begingroup\$ @user80551 I don't need root access for this. \$\endgroup\$
    – Flonk
    May 28, 2014 at 13:38
  • 11
    \$\begingroup\$ hmm... ./foo mbox \$\endgroup\$
    – Izkata
    May 28, 2014 at 16:06
256
\$\begingroup\$

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.

\$\endgroup\$
9
  • 5
    \$\begingroup\$ Wow... that is really interesting. \$\endgroup\$
    – ojblass
    May 28, 2014 at 4:55
  • 33
    \$\begingroup\$ @JackM: It will, but that's explicitly allowed in the question. \$\endgroup\$
    – Dennis
    May 28, 2014 at 19:46
  • 36
    \$\begingroup\$ @JackM, that seems like a great way to stop the "script" from running. \$\endgroup\$ Jun 1, 2014 at 2:21
  • 6
    \$\begingroup\$ 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. \$\endgroup\$
    – zwol
    Jun 2, 2014 at 2:28
  • 5
    \$\begingroup\$ @RosLuP 209 different users, apparently. If you disagree, downvote and move on. \$\endgroup\$
    – Dennis
    May 30, 2017 at 17:41
157
\$\begingroup\$

Bash, 5

>"$0"

Truncates itself to zero length.

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

\$\endgroup\$
3
  • 2
    \$\begingroup\$ 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! \$\endgroup\$
    – apenwarr
    Jun 8, 2014 at 5:30
  • 3
    \$\begingroup\$ @apenwarr it says "$0: ambiguous redirect" when without quotes and the filename contains spaces \$\endgroup\$
    – user16402
    Jun 8, 2014 at 6:34
  • 3
    \$\begingroup\$ @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. \$\endgroup\$
    – sch
    May 4, 2016 at 12:55
151
\$\begingroup\$

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.

\$\endgroup\$
5
  • 8
    \$\begingroup\$ I never thought of it before but you are absolutely correct. \$\endgroup\$
    – ojblass
    May 29, 2014 at 1:34
  • \$\begingroup\$ very interesting \$\endgroup\$ May 29, 2014 at 7:54
  • 12
    \$\begingroup\$ "Warning: location of gzip may vary" — this isn't code-golf, so you can use #!/usr/bin/env gzip \$\endgroup\$
    – wchargin
    Jun 1, 2014 at 4:39
  • 44
    \$\begingroup\$ +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. \$\endgroup\$
    – clapp
    Jul 22, 2015 at 8:19
  • 1
    \$\begingroup\$ It's essentially a file that, when called, hides itself in a box and refuses to come out until you forcibly unpack it. made me laughing. :D \$\endgroup\$
    – Mischa
    Jul 26, 2017 at 15:31
125
\$\begingroup\$

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
\$\endgroup\$
6
  • 4
    \$\begingroup\$ chmod 0 works too \$\endgroup\$
    – gnibbler
    May 28, 2014 at 11:06
  • \$\begingroup\$ @gnibbler thnx, added \$\endgroup\$
    – user16402
    May 28, 2014 at 11:09
  • \$\begingroup\$ I think you can call the program a and save yet 3 chars: chmod 0 a \$\endgroup\$
    – yo'
    Jun 3, 2014 at 11:54
  • \$\begingroup\$ @tohecz that's basically cheating though \$\endgroup\$
    – user16402
    Jun 3, 2014 at 12:48
  • 6
    \$\begingroup\$ Even nicer #!/bin/chmod 0 \$\endgroup\$
    – Hauleth
    Jun 5, 2014 at 23:28
118
\$\begingroup\$

6800 machine code - 1 byte

0xDD

This is known as HCF or Halt and Catch Fire

\$\endgroup\$
2
  • 83
    \$\begingroup\$ 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! \$\endgroup\$
    – Hakanai
    Jun 2, 2014 at 13:01
  • \$\begingroup\$ Catch fire and no more cpu, so code will run once :)) \$\endgroup\$
    – raspiduino
    Jun 10, 2021 at 7:10
99
\$\begingroup\$

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
\$\endgroup\$
1
  • 3
    \$\begingroup\$ How about sed -i g $0? \$\endgroup\$
    – seshoumara
    Sep 3, 2016 at 12:19
96
\$\begingroup\$

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.

\$\endgroup\$
5
  • 1
    \$\begingroup\$ Does poke simply move a variable to a location? \$\endgroup\$
    – ojblass
    May 29, 2014 at 1:30
  • 14
    \$\begingroup\$ @ojblass yes, effectively. poke a, b is equivalent to the C code *((unsigned char *)a) = b;. \$\endgroup\$
    – Jules
    May 29, 2014 at 5:54
  • 4
    \$\begingroup\$ I'd like to visualise my FaceBook pokes that way! \$\endgroup\$ Jun 6, 2014 at 9:58
  • 3
    \$\begingroup\$ Oh wow... I remember PEEK and POKE from C64 BASIC! I was writing this stuff around 1977. \$\endgroup\$
    – Fixee
    Jul 5, 2014 at 19:34
  • \$\begingroup\$ side note: A 0 byte is used to mark the end of code lines; so address 0x800 probably needs one to mark the beginning of the first code line. \$\endgroup\$
    – Titus
    Mar 13, 2018 at 15:41
94
\$\begingroup\$

Assumption: Running Solaris, logged in as root

killall
\$\endgroup\$
10
  • 3
    \$\begingroup\$ does solaris really have such a thing? \$\endgroup\$
    – ojblass
    May 28, 2014 at 4:00
  • 23
    \$\begingroup\$ Yes, it does just what it says on the tin and kills all running processes. \$\endgroup\$ May 28, 2014 at 4:01
  • \$\begingroup\$ one upvote for you! \$\endgroup\$
    – ojblass
    May 28, 2014 at 4:01
  • 11
    \$\begingroup\$ 1, The question mentions no root access is permitted. \$\endgroup\$
    – user80551
    May 28, 2014 at 13:36
  • 129
    \$\begingroup\$ @user80551 he's the reason for that rule. \$\endgroup\$
    – Seiyria
    May 28, 2014 at 14:58
75
\$\begingroup\$

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 ;)

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

Python, 18

open(__file__,'w')

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

\$\endgroup\$
6
  • 15
    \$\begingroup\$ 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. \$\endgroup\$
    – Bob
    May 29, 2014 at 17:50
  • 7
    \$\begingroup\$ 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. \$\endgroup\$
    – Bob
    May 29, 2014 at 23:09
  • 6
    \$\begingroup\$ 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. \$\endgroup\$
    – Schilcote
    May 31, 2014 at 19:59
  • 1
    \$\begingroup\$ This could be shortened to something like open("f.py","w"). \$\endgroup\$ Jun 18, 2015 at 4:56
  • 1
    \$\begingroup\$ Doesn't cease to work whrn .pyc remains \$\endgroup\$
    – minmaxavg
    Apr 10, 2016 at 7:25
60
\$\begingroup\$

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
\$\endgroup\$
4
  • 8
    \$\begingroup\$ So if you run it a lot of times, you get the Batman theme. +1 for that. \$\endgroup\$ Jun 9, 2017 at 10:59
  • 3
    \$\begingroup\$ @Hankrecords Sadly, not really, since this is not gonna execute later... \$\endgroup\$
    – RedClover
    Sep 29, 2017 at 14:55
  • \$\begingroup\$ @Soaku Bummer... \$\endgroup\$ Sep 29, 2017 at 15:10
  • \$\begingroup\$ @Hankrecords unless you remove eval, but then it won't fulfill this challenge \$\endgroup\$
    – RedClover
    Sep 30, 2017 at 16:16
49
\$\begingroup\$

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.

\$\endgroup\$
47
\$\begingroup\$

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

\$\endgroup\$
9
  • \$\begingroup\$ Darn it :D I just had the same idea :P \$\endgroup\$
    – Knerd
    May 28, 2014 at 8:22
  • 2
    \$\begingroup\$ :(){ :&};: 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);. \$\endgroup\$
    – marinus
    May 28, 2014 at 9:28
  • 31
    \$\begingroup\$ Wow! those are some deadly emoticions! I best not call my computer bignosed frownyface :(){ .... \$\endgroup\$ May 28, 2014 at 22:27
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Brilliand
    May 30, 2014 at 21:53
  • 14
    \$\begingroup\$ 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). \$\endgroup\$
    – Ben Voigt
    May 31, 2014 at 19:45
45
\$\begingroup\$

Commodore 64 BASIC

0 NEW

NEW deletes the program.

\$\endgroup\$
7
  • 1
    \$\begingroup\$ What's that do? \$\endgroup\$ May 28, 2014 at 16:52
  • 3
    \$\begingroup\$ @user973810 if i remember basic, new is for cleaning memory, so it will delete program \$\endgroup\$
    – user902383
    May 28, 2014 at 17:08
  • 3
    \$\begingroup\$ Nice. Not specific to Commodore 64, probably works as is on almost every 8-bit BASIC machine from the 80's... \$\endgroup\$
    – ysap
    Jun 5, 2014 at 22:56
  • 1
    \$\begingroup\$ 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 :) \$\endgroup\$ Jun 8, 2014 at 22:42
  • 3
    \$\begingroup\$ @ysap: It would be more portable if it were using 1 as line number; not all BASIC implementations supported line number 0. \$\endgroup\$
    – celtschk
    Jun 22, 2014 at 14:38
21
\$\begingroup\$

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"
});
\$\endgroup\$
2
  • 7
    \$\begingroup\$ At last, a C# answer! \$\endgroup\$
    – Pharap
    Jun 4, 2014 at 17:44
  • \$\begingroup\$ Why is choice required? \$\endgroup\$
    – wizzwizz4
    May 5, 2016 at 15:33
20
\$\begingroup\$

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;}
"Goodbye"
rm $(.{$MyInvocation.ScriptName})
\$\endgroup\$
2
  • \$\begingroup\$ Explanation, please? \$\endgroup\$ Dec 31, 2016 at 17:37
  • \$\begingroup\$ @noɥʇʎԀʎzɐɹƆ Lines till 13 are just nonsense. After that, like any other shell, PowerShell loads the running script into memory and thus it no longer needs the original script file...so it deletes itself. \$\endgroup\$ Jan 2, 2017 at 0:59
18
\$\begingroup\$

Bash (5)

rm $0

Assuming you don't have spaces in the filename.

\$\endgroup\$
2
  • 45
    \$\begingroup\$ This is why Unix is better than Windows: rm instead of del saved you a byte. \$\endgroup\$
    – MadTux
    Jun 10, 2014 at 19:04
  • 1
    \$\begingroup\$ @MadTux I prefer *nix to Unix. \$\endgroup\$
    – wizzwizz4
    May 5, 2016 at 15:36
18
\$\begingroup\$

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;
}
\$\endgroup\$
12
  • 12
    \$\begingroup\$ @Templar in the context of JavaScript, I think that refreshing the page counts as rebooting (maybe?) \$\endgroup\$
    – user16402
    May 28, 2014 at 9:41
  • 2
    \$\begingroup\$ Even if you weren't removing the script from the page, it would still only execute once. There's no point to this. \$\endgroup\$
    – nderscore
    May 28, 2014 at 13:06
  • 2
    \$\begingroup\$ @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();">. \$\endgroup\$
    – Bob
    May 30, 2014 at 4:07
  • 5
    \$\begingroup\$ 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}? \$\endgroup\$
    – Keen
    May 30, 2014 at 18:59
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – Ben Voigt
    Jun 1, 2014 at 5:50
15
\$\begingroup\$

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.


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.

<?php
$db = pg_connect("[connection information]");
$ip = isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];

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

CREATE TABLE users (
    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.

\$\endgroup\$
14
  • 4
    \$\begingroup\$ I'd argue that this will run multiple times, it just produces no output after the first. \$\endgroup\$
    – Brilliand
    May 30, 2014 at 21:56
  • 7
    \$\begingroup\$ That didn't even once show "Hello World" for me. \$\endgroup\$ Jun 1, 2014 at 0:13
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Jan 7, 2016 at 15:46
  • 1
    \$\begingroup\$ @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. \$\endgroup\$ Jan 8, 2016 at 17:07
  • 3
    \$\begingroup\$ I believe that this is a violation of a standard loophole: Outsourcing the real answer. \$\endgroup\$
    – Joseph
    Jan 5, 2018 at 22:40
13
\$\begingroup\$

PHP, 22 20 chars

<?=unlink(__FILE__);

EDIT: Removed two chars at end per comments.

\$\endgroup\$
5
  • 2
    \$\begingroup\$ This can be further simplified as: <?unlink(__FILE__);, the trailing ?> is not required \$\endgroup\$
    – leepowers
    Jun 8, 2014 at 3:54
  • \$\begingroup\$ You have to start with <?= or the start tag is not recognized. \$\endgroup\$ Jun 8, 2014 at 12:13
  • 2
    \$\begingroup\$ PHP destroying itself...ha! E_NOTICE line 3048 \$\endgroup\$
    – metadings
    Jun 8, 2014 at 15:46
  • \$\begingroup\$ <?+space is also ok. You just cannot use a letter after the short tag. \$\endgroup\$
    – Titus
    Jan 17, 2017 at 2:56
  • \$\begingroup\$ You can save one more byte by naming the file. <?=unlink("a.php"); \$\endgroup\$ Jun 22, 2021 at 17:14
10
\$\begingroup\$

Ruby,14

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

IO.write $0,$0
\$\endgroup\$
6
  • 4
    \$\begingroup\$ And what if the program is named "IO.write $0,$0"? "Assumption: Name the program something that isn't valid code in any language." \$\endgroup\$
    – Brilliand
    May 30, 2014 at 21:57
  • 1
    \$\begingroup\$ @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. \$\endgroup\$
    – Mohammad
    Jun 1, 2014 at 9:28
  • 5
    \$\begingroup\$ @Mhmd a ruby program can end with anything. For example gem and irb are Ruby programs with no extension. \$\endgroup\$
    – bfontaine
    Jun 8, 2014 at 9:13
  • 2
    \$\begingroup\$ @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). \$\endgroup\$
    – bfontaine
    May 6, 2016 at 7:52
  • 1
    \$\begingroup\$ @bfontaine That they can doesn't mean they should. If they have shebangs it's clear what they will run in: an extension should be used if not. (An extension should always be used, but it isn't as important if you have a shebang.) \$\endgroup\$
    – wizzwizz4
    May 6, 2016 at 16:06
10
\$\begingroup\$

Bash 9 8 Characters

nc -l 1&

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

\$\endgroup\$
5
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ May 29, 2014 at 21:22
  • \$\begingroup\$ nc -l 1& would fix the problem with 0 and be one byte shorter, since the last space is not needed. \$\endgroup\$
    – kasperd
    Jun 1, 2014 at 14:59
  • \$\begingroup\$ @kasperd Thanks for the input :-) \$\endgroup\$
    – Falco
    Jun 2, 2014 at 7:40
  • \$\begingroup\$ @heinrich5991 ok - than I would need 11 chars without root access to use a Port like 9654 \$\endgroup\$
    – Falco
    Jun 2, 2014 at 7:41
  • \$\begingroup\$ Care to explain why you downvoted ? \$\endgroup\$
    – Falco
    Jun 22, 2014 at 22:57
9
\$\begingroup\$

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
\$\endgroup\$
9
\$\begingroup\$

NodeJS - 33 bytes

require('fs').unlink(__filename);
\$\endgroup\$
3
  • \$\begingroup\$ Could you describe what this does for those who are unfamiliar with the language? \$\endgroup\$
    – Kyle Kanos
    May 30, 2014 at 17:38
  • 1
    \$\begingroup\$ @KyleKanos It gets the filesystem module fs and the current filename __filename and removes that filename from the filesystem. \$\endgroup\$
    – Keen
    May 30, 2014 at 19:06
  • 8
    \$\begingroup\$ You can elide the semicolon because they are optional in JavaScript. \$\endgroup\$
    – nalply
    Jun 1, 2014 at 12:07
9
\$\begingroup\$

Batch, 7 chars

Save unsaved work before trying this.

Assumes either a 64-bit system, or a 32-bit system with <2 GB RAM memory. Must be saved to a .bat or .cmd file before being launched, just entering it in cmd.exe won't work.

^ nul<^

It consumes a full CPU core and fills your RAM memory at a rate of several hundred megabytes per second. If you don't stop it in time (Task Manager), it will consume every byte of RAM on your computer, your entire system will freeze and you can't do anything before you forcibly shut down and restart your computer by means of cutting power or holding the power button down.

All credits go to txtechhelp on StackOverflow for this, see more information here: https://stackoverflow.com/q/23284131/1955334

\$\endgroup\$
4
  • \$\begingroup\$ How would this be possible ? What about paging ? Process priority ? \$\endgroup\$ Jun 3, 2014 at 18:17
  • \$\begingroup\$ I ran this script, nothing happened. \$\endgroup\$
    – Pavel
    Dec 1, 2016 at 0:49
  • \$\begingroup\$ @Pavel I'd guess it's fixed in Windows 10 then. I cannot reproduce it on Windows 10, but it works on Windows 8.1. \$\endgroup\$
    – bilde2910
    Dec 11, 2016 at 22:03
  • 1
    \$\begingroup\$ "It consumes a full CPU core and fills your RAM memory at a rate of several hundred megabytes per second. If you don't stop it in time (Task Manager), it will consume every byte of RAM on your computer, your entire system will freeze and you can't do anything before you forcibly shut down and restart your computer by means of cutting power or holding the power button down." Sounds like a horror story for computers... \$\endgroup\$ Dec 31, 2016 at 17:38
9
\$\begingroup\$

GW-BASIC, 20 bytes

1 COLOR 3
2 SCREEN 1

This is a fun one. COLOR 3 sets the foreground color to cyan. SCREEN 1 sets the output screen to one that does not have color. Therefore, you can run the program once, but if you try to run it again:

gif

\$\endgroup\$
8
\$\begingroup\$

Sinclair BASIC

10 POKE 23635,255

Moves the address of the BASIC program in memory away from where it should be (203) so the wrong data is found by the interpreter.

\$\endgroup\$
7
\$\begingroup\$

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.

\$\endgroup\$
6
  • \$\begingroup\$ Posted after this became a popularity contest \$\endgroup\$ May 30, 2014 at 5:31
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – orion
    May 30, 2014 at 9:14
  • \$\begingroup\$ Does the file still exist afterwards? \$\endgroup\$ May 30, 2014 at 16:34
  • \$\begingroup\$ I now completely changed the Bash example. \$\endgroup\$ May 30, 2014 at 18:03
  • \$\begingroup\$ How are these not destructive? \$\endgroup\$
    – ysap
    Jun 5, 2014 at 23:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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