Code that will only execute once

225

88

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.

ojblass

Posted 2014-05-28T03:40:21.427

Reputation: 2 575

4echo "This program prints gullible if it is executed again." – totallyhuman – 2017-05-10T21:53:21.770

5

possible duplicate of A program that deletes itself

– Peter Taylor – 2014-05-28T07:04:47.477

7@PeterTaylor a possible Solution would be the a self delete but as the result are showing it isn't the only one. – Lukei – 2014-05-28T07:21:19.987

1Is it ok, if the programm shuts the PC down? – Knerd – 2014-05-28T08:54:29.063

No restarting the computer is equivalent to halt. – ojblass – 2014-05-28T13:10:49.400

2I feel that this would be much more interesting as a popularity-contest type question. Perhaps ask it again, or a similar one. Too many simple low character count winners that are already answered in the program that deletes itself question. – agweber – 2014-05-28T14:16:18.080

this is now a popularity contest. – ojblass – 2014-05-28T14:18:16.990

102To 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 – 2014-05-28T20:41:27.110

I feel like this would be much more interesting if the original script had to be able to do something useful. Using the shebang line to mangle or remove the file is a funny interpretation of the original question, but doesn't really allow executing a "script" in the popular meaning of some Turing-complete code. – l0b0 – 2014-05-30T14:49:36.223

6The site is free for you to propose such a question. – ojblass – 2014-05-30T22:40:44.380

3I suspect it will be closed as a duplicate. – l0b0 – 2014-06-01T07:52:32.217

Trapdoors! Don't you all remember Jurassic Park (book, not movie)? – Carl Witthoft – 2014-06-04T15:17:43.383

16echo "If you try to execute me again, it means you are an idiot."; <-- Nobody will execute more than once :P – user3459110 – 2014-06-05T12:45:15.200

4@orion You misspelled "emacs". – David Conrad – 2014-06-06T20:19:15.503

26Would missile-related software have qualified? ;) – rsegal – 2014-06-08T04:28:34.970

4fork bomb? :(){ :|: & };: – Stephen – 2014-06-08T23:52:46.860

@l0b0 see http://codegolf.stackexchange.com/a/28747/16411

– Bill Woodger – 2014-06-10T10:13:41.590

Answers

518

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

Martin Ender

Posted 2014-05-28T03:40:21.427

Reputation: 184 808

117No doubt, this deserves to win. – Matteo Italia – 2014-05-28T10:44:53.920

78Finally, a sufficiently vigilant language for the modern age! I'm going to start using it in production. All bugs must be purged. – Claudiu – 2014-05-28T15:55:19.707

13To 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 – 2014-05-28T18:23:08.660

10

@JonathanPullano you're not the first one to notice that ;)

– Martin Ender – 2014-05-28T18:24:17.507

33Additional points for swearing. A program making a confident false statement no doubt needs to be eliminated. – orion – 2014-05-28T20:49:02.943

Congratulation for winning and thank you for participating. – ojblass – 2014-06-01T01:06:54.910

4Omg this language is awesome! – MasterMastic – 2014-06-01T11:50:42.537

Granted, it's not code-golf, but how about a simple def main():x which will NameError? – Nick T – 2014-06-01T17:48:11.497

1@NickT ah, good point. This answer was never competitive for code golf with all those 4 to 6 character answers, so I went for something simple and neat, but didn't really care about properly golfing it down. (You can see in the edit history that there was a stage where I actually said "heck, this isn't winning anyway, but I'm posting it for the fun of it" back when the challenge actually was code golf.) – Martin Ender – 2014-06-01T17:53:28.567

@JonathanPullano Unless that function is main. – primo – 2014-06-02T19:49:21.870

Would main=lambda:0/0 work? – ɐɔıʇǝɥʇuʎs – 2014-06-03T18:59:34.743

295

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.

Flonk

Posted 2014-05-28T03:40:21.427

Reputation: 7 621

2You can golf it to 4 bytes by removing the /bin/ – LukStorms – 2015-09-13T11:27:17.237

@Ourous You were very correct when you posted this! +1 – Erik the Outgolfer – 2016-04-23T07:22:38.797

@celtschk But then it would need to be invoked as ./less and not less. – cat – 2016-05-03T23:20:25.097

@cat, not if it were added to the $PATH environment variable ahead of the real one. – Wildcard – 2016-05-04T04:10:08.733

@LukStorms, but then that would only work if the current working directory of the process that executes that script contains an executable file called rm that removes the file it is given as argument (or any other behaviour that answers the question) (like /bin on most Unix-like systems). – sch – 2016-05-04T12:39:44.490

1Technically, when you're creating that file with ed, you're adding a newline character, so that makes 10 chars in total. Without the newline (printf '#!/bin/rm' > foo), it still works on Linux or Solaris for instance, but not on FreeBSD (unless invoked from zsh which will parse the she-bang itself after the system return ENOEXEC because of the missing newline) – sch – 2016-05-04T13:04:46.447

1Strictly speaking this is an rm script, the language should be rm. – user253751 – 2016-08-01T20:53:56.530

For those that don't know Linux, what does this do? – Nzall – 2014-05-28T11:09:16.943

9Without ever having used Linux myself, I think it deletes the script file. – Οurous – 2014-05-28T11:23:56.773

58@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 – None – 2014-05-28T11:27:28.187

@NateKerkhofs yup, professorfish is pretty much spot on. I've included a little explanation in the post aswell. – Flonk – 2014-05-28T12:02:57.980

20This is hysterical – ojblass – 2014-05-28T13:13:45.963

-1, The question mentions no root access is permitted. – user80551 – 2014-05-28T13:36:09.843

26@user80551 I don't need root access for this. – Flonk – 2014-05-28T13:38:36.713

@Flonk Oh, sorry, I misunderstood this and thought you were deleting /bin/rm itself; retracted my down-vote. EDIT: Turns out I can't retract it now unless you edit your answer. – user80551 – 2014-05-28T13:44:07.123

9hmm... ./foo mbox – Izkata – 2014-05-28T16:06:13.397

1Not Linux specific, should pretty much work on every unixoid system. – David Ongaro – 2014-05-29T07:18:08.053

1This should even work in cygwin on Windows – slebetman – 2014-05-30T06:56:39.853

@Izkata Or ./foo -rf / [My conscience leads me to warn people not to try this to see what it does.] – Jim Balter – 2014-06-04T13:58:56.007

6@yoniLavi Why? Real programmers use cat :) – MadTux – 2014-06-10T18:54:52.663

7Of course, the really evil use would to give it a name of a commonly used command (like less) and put it in the path before the real one ... then the next time the affected user does less foo.txt, the file foo.txt will disappear, and since the script gets deleted as well, the victim will have no way to find out why. – celtschk – 2014-06-22T14:32:03.383

@slebetman Indeed it works on Cygwin, I tested it (Windows 8 64-bit). – Alex – 2014-07-15T16:02:53.227

243

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.

Dennis

Posted 2014-05-28T03:40:21.427

Reputation: 196 637

200 upvotes \o/ nice answer :D – HyperNeutrino – 2017-04-21T04:24:52.710

For who this is interesting? The one want to stop the PC... – RosLuP – 2017-05-30T17:33:04.783

4@RosLuP 209 different users, apparently. If you disagree, downvote and move on. – Dennis – 2017-05-30T17:41:12.720

4Wow... that is really interesting. – ojblass – 2014-05-28T04:55:50.067

Pulling the power cable and restarting won't fix it? – Jack M – 2014-05-28T18:35:29.650

31@JackM: It will, but that's explicitly allowed in the question. – Dennis – 2014-05-28T19:46:42.700

2@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 – 2014-05-28T20:11:44.450

35@JackM, that seems like a great way to stop the "script" from running. – Paul Draper – 2014-06-01T02:21:23.593

5I 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 – 2014-06-02T02:28:55.813

150

Bash, 5

>"$0"

Truncates itself to zero length.

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

user16402

Posted 2014-05-28T03:40:21.427

Reputation:

1@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 – 2016-05-04T12:55:36.733

2Actually, 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 – 2014-06-08T05:30:54.250

3@apenwarr it says "$0: ambiguous redirect" when without quotes and the filename contains spaces – None – 2014-06-08T06:34:43.250

144

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.

orion

Posted 2014-05-28T03:40:21.427

Reputation: 3 095

37+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. – clap – 2015-07-22T08:19:41.380

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 – Mischa – 2017-07-26T15:31:20.900

7I never thought of it before but you are absolutely correct. – ojblass – 2014-05-29T01:34:58.517

very interesting – Grijesh Chauhan – 2014-05-29T07:54:33.203

11"Warning: location of gzip may vary" — this isn't [tag:code-golf], so you can use #!/usr/bin/env gzip – wchargin – 2014-06-01T04:39:19.507

121

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

user16402

Posted 2014-05-28T03:40:21.427

Reputation:

Take chmod 0 * for 9 bytes. – Titus – 2016-11-21T14:06:41.193

4chmod 0 works too – gnibbler – 2014-05-28T11:06:30.727

@gnibbler thnx, added – None – 2014-05-28T11:09:15.847

I think you can call the program a and save yet 3 chars: chmod 0 a – yo' – 2014-06-03T11:54:36.117

@tohecz that's basically cheating though – None – 2014-06-03T12:48:55.383

5Even nicer #!/bin/chmod 0 – Hauleth – 2014-06-05T23:28:40.960

113

6800 machine code - 1 byte

0xDD

This is known as HCF or Halt and Catch Fire

gnibbler

Posted 2014-05-28T03:40:21.427

Reputation: 14 170

78Well, 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 – 2014-06-02T13:01:02.410

95

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

Digital Trauma

Posted 2014-05-28T03:40:21.427

Reputation: 64 644

3How about sed -i g $0? – seshoumara – 2016-09-03T12:19:00.510

92

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.

Danko Durbić

Posted 2014-05-28T03:40:21.427

Reputation: 10 241

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. – Titus – 2018-03-13T15:41:02.487

1Does poke simply move a variable to a location? – ojblass – 2014-05-29T01:30:52.673

12@ojblass yes, effectively. poke a, b is equivalent to the C code *((unsigned char *)a) = b;. – Jules – 2014-05-29T05:54:04.243

4I'd like to visualise my FaceBook pokes that way! – Sunny R Gupta – 2014-06-06T09:58:33.800

3Oh wow... I remember PEEK and POKE from C64 BASIC! I was writing this stuff around 1977. – Fixee – 2014-07-05T19:34:55.073

89

Assumption: Running Solaris, logged in as root

killall

Greg Hewgill

Posted 2014-05-28T03:40:21.427

Reputation: 2 641

3does solaris really have such a thing? – ojblass – 2014-05-28T04:00:45.607

22Yes, it does just what it says on the tin and kills all running processes. – Greg Hewgill – 2014-05-28T04:01:16.287

one upvote for you! – ojblass – 2014-05-28T04:01:56.790

i can beat you though... you ready? – ojblass – 2014-05-28T04:02:29.203

alright just for you... made it harder now I am thinking too – ojblass – 2014-05-28T04:08:57.920

how many characters does it take to fill the file system up? – ojblass – 2014-05-28T04:09:45.107

91, The question mentions no root access is permitted. – user80551 – 2014-05-28T13:36:53.453

119@user80551 he's the reason for that rule. – Seiyria – 2014-05-28T14:58:02.473

Don't worry, Linuxes has the command too: killall5. It's in /sbin so only on root's path in Debuntu. – FauxFaux – 2014-06-02T21:16:46.740

@FauxFaux killall5 kills not all processes, only those not in current session and not kernel threads. – Ruslan – 2014-06-03T13:54:35.863

69

Python, 18

open(__file__,'w')

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

segfaultd

Posted 2014-05-28T03:40:21.427

Reputation: 1 189

1This could be shortened to something like open("f.py","w"). – Ethan Bierlein – 2015-06-18T04:56:34.790

1Doesn't cease to work whrn .pyc remains – minmaxavg – 2016-04-10T07:25:23.770

14Just 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 – 2014-05-29T17:50:06.650

@Bob I thought the file was only written when you .close()'d it. Thanks for the info! – segfaultd – 2014-05-29T22:38:18.297

7I 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 – 2014-05-29T23:09:01.717

5The "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 – 2014-05-31T19:59:52.337

67

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

Knerd

Posted 2014-05-28T03:40:21.427

Reputation: 1 251

4It doens't crash the computer instantly. I can actually run this multiple times on a windows machine before it starts to catch fire. – Rob – 2015-12-08T16:07:43.283

What did I do to my computer :( – Skyl3r – 2016-02-12T19:23:40.510

1Question: does running this actually do anything that's not fixable by a restart? The comments are worrying me. – Pavel – 2016-12-01T00:41:08.900

It is a classic forkbomb, it will kill the computer and than you should restart it and all is fine. – Knerd – 2016-12-02T09:47:57.970

I was hoping to find this in the answers. +1 :) – Hankrecords – 2017-06-09T10:58:15.433

After I executed it on my PC, my second monitor stopped working! :O Windows cannot detect it, what have you done? – RedClover – 2017-09-30T16:15:33.407

@Knerd Nothing happened to my computer :) My computer screen closed when I ran this forkbomb for a while, and when I opened my screen the program is still running (it did not stop); it seems that nothing has happened. – None – 2019-07-28T14:27:17.053

85Is there a productive windows environment? (I'm joking of course). – orion – 2014-05-28T20:25:49.353

17it looks so innocent! – ojblass – 2014-05-29T13:01:33.903

2Yeah it does, I actually got tricked once -.- – Knerd – 2014-05-29T17:34:08.943

16Ok, definitely don't try that. It didn't go well. – rmobis – 2014-06-03T15:14:42.097

@JimBalter thank you :D – Knerd – 2014-06-04T14:19:28.870

76Don't have the rep to downvote, but it violates "runs only once" in the most severe way possible. – Xan – 2014-06-06T09:53:56.200

@Xan Why? You start it once and then it crashes the computer. I know, it starts itself twice, but how does it violate the rule? – Knerd – 2014-06-06T10:01:05.860

1Statement: "The goal of this challenge is to write code that will execute once and only once". Your code explicitly executes itself again. – Xan – 2014-06-06T10:08:58.630

@ojblass would you please decide if it is ok or not? – Knerd – 2014-06-06T11:16:00.077

14I believe a human only executes it once and that it qualifies. – ojblass – 2014-06-06T12:17:42.923

55

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

Casey Chu

Posted 2014-05-28T03:40:21.427

Reputation: 1 661

5So if you run it a lot of times, you get the Batman theme. +1 for that. – Hankrecords – 2017-06-09T10:59:04.260

2@Hankrecords Sadly, not really, since this is not gonna execute later... – RedClover – 2017-09-29T14:55:43.110

@Soaku Bummer... – Hankrecords – 2017-09-29T15:10:11.247

@Hankrecords unless you remove eval, but then it won't fulfill this challenge – RedClover – 2017-09-30T16:16:27.570

46

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.

Bill Woodger

Posted 2014-05-28T03:40:21.427

Reputation: 1 391

44

Commodore 64 BASIC

0 NEW

NEW deletes the program.

Danko Durbić

Posted 2014-05-28T03:40:21.427

Reputation: 10 241

Also GO64 command on Commodore 128 could apply to the contest – Voitcus – 2015-06-26T05:25:43.397

@MattWarren OLD might be C128 Basic (Commodore Basic V7.0), but the C64 (Commodore Basic V2) definitely did not have it. – Titus – 2016-11-21T14:11:48.290

1What's that do? – Darth Egregious – 2014-05-28T16:52:13.300

3@user973810 if i remember basic, new is for cleaning memory, so it will delete program – user902383 – 2014-05-28T17:08:32.833

3Nice. Not specific to Commodore 64, probably works as is on almost every 8-bit BASIC machine from the 80's... – ysap – 2014-06-05T22:56:34.567

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 – 2014-06-08T22:42:04.250

3@ysap: It would be more portable if it were using 1 as line number; not all BASIC implementations supported line number 0. – celtschk – 2014-06-22T14:38:26.067

42

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

user80551

Posted 2014-05-28T03:40:21.427

Reputation: 2 520

Darn it :D I just had the same idea :P – Knerd – 2014-05-28T08:22:10.657

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 – 2014-05-28T09:28:18.900

@marinus Open up system monitor and run it for a few minutes. Your memory usage should increase very slowly. The command does quit though so you can easily run it again before reaching OOM. – user80551 – 2014-05-28T13:47:57.443

27Wow! those are some deadly emoticions! I best not call my computer bignosed frownyface :(){ .... – Level River St – 2014-05-28T22:27:45.610

1If 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 – 2014-05-30T21:53:51.180

@Brilliand Of course it's possible to fight it. This also assumes that ulimit's haven't been set (or anything else to prevent this in the first place). – user80551 – 2014-05-31T04:46:24.910

11I 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 – 2014-05-31T19:45:11.260

@BenVoigt The entire script includes defining the function. The function is just getting executed many times. Defining the function would be reasonably difficult in the short time that you have before reaching OOM. – user80551 – 2014-06-01T05:42:03.260

@user80551 I suppose actively working to repair the damage without a reboot doesn't count, but I think simply trying to run the script again every few seconds until it succeeds does. – Brilliand – 2014-06-02T15:22:41.147

20

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

BenVlodgi

Posted 2014-05-28T03:40:21.427

Reputation: 361

Why is choice required? – wizzwizz4 – 2016-05-05T15:33:48.187

7At last, a C# answer! – Pharap – 2014-06-04T17:44:56.483

19

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

bacchusbeale

Posted 2014-05-28T03:40:21.427

Reputation: 1 235

1You should add an assumption of running on Unix environment on the C++ entry. chmod doesn't exist in Windows environment. – Khaled.K – 2016-04-20T12:07:23.103

Can't I just refresh the page and rerun the code? – Lukei – 2014-05-28T07:15:33.567

11@Templar in the context of JavaScript, I think that refreshing the page counts as rebooting (maybe?) – None – 2014-05-28T09:41:14.337

2Even if you weren't removing the script from the page, it would still only execute once. There's no point to this. – nderscore – 2014-05-28T13:06:45.373

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 – 2014-05-30T04:07:02.907

Bob, yes the function h must be called from onload or another event e.g onclick. – bacchusbeale – 2014-05-30T12:12:36.957

4Given 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 – 2014-05-30T18:59:57.187

If you need to rearrange the #s element, it should be okay to just do h=s.innerHTML=s.innerHTML.replace("h","g"). – Keen – 2014-05-30T19:03:37.317

1With #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 – 2014-06-01T05:50:42.130

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 – 2014-06-04T17:35:54.637

@nmclean You could still use the debug console to execute it a second time, but this actually deletes itself – None – 2014-06-04T18:15:06.077

1@professorfish We can only call the function again, not re-execute the script. If we're permitting code structures that execute only once as well as actual scripts, we could have just solved this with a conditional. Maybe we could say HTML with multiple script tags referencing the same src counts as multiple execution attempts, and have the script remove the container element so only the first attempt succeeds. – nmclean – 2014-06-04T18:37:13.593

19

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

SomeShinyObject

Posted 2014-05-28T03:40:21.427

Reputation: 953

Explanation, please? – noɥʇʎԀʎzɐɹƆ – 2016-12-31T17:37:05.790

@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. – SomeShinyObject – 2017-01-02T00:59:24.197

18

Bash (5)

rm $0

Assuming you don't have spaces in the filename.

marinus

Posted 2014-05-28T03:40:21.427

Reputation: 30 224

1@MadTux I prefer *nix to Unix. – wizzwizz4 – 2016-05-05T15:36:23.200

40This is why Unix is better than Windows: rm instead of del saved you a byte. – MadTux – 2014-06-10T19:04:02.223

14

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.

Konrad Borowski

Posted 2014-05-28T03:40:21.427

Reputation: 11 185

Hum, Google does not know a lot about this URL. What's the point of that runonce "service"? @xfix, is it something you wrote on purpose, or some service made by heroku? In the second case I guess it's intended to be called from hosted services of some sort. Does it only remember IP between calls? What if another unrelated person/program happens to get the same IP as a previous person/program that already called runonce? Is there a way to undo the call? – Stéphane Gourichon – 2016-01-04T20:07:47.837

1@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. – Konrad Borowski – 2016-01-07T15:46:24.610

@xfix Thanks, this answers my questions. Beware of security implications ref1 ref2 (see comment by ONOZ) ref3. Needing Internet access and the heroku infrastructure to run code once makes a geeky overkill funny hacky way to answer the challenge anyway. :o)

– Stéphane Gourichon – 2016-01-07T17:15:25.933

What does runonce.herokuapp.com do on a request where (ref http://stackoverflow.com/a/4262098/1429390 ) X-Forwarded-For header, for example, is always set to '; DROP TABLE users;--? Is it protected against injections attack by the use of pg_query_params and the array parameter? (Notice this is drifting out of topic.)

– Stéphane Gourichon – 2016-01-07T17:18:17.453

1@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. – Konrad Borowski – 2016-01-08T17:07:55.823

2

I believe that this is a violation of a standard loophole: Outsourcing the real answer.

– juniorRubyist – 2018-01-05T22:40:44.840

@juniorRubyist Yeah, you're right. This answer was created before that loophole post existed – Konrad Borowski – 2018-01-10T09:53:23.100

4I'd argue that this will run multiple times, it just produces no output after the first. – Brilliand – 2014-05-30T21:56:36.813

5That didn't even once show "Hello World" for me. – Paŭlo Ebermann – 2014-06-01T00:13:41.137

@PaŭloEbermann: Perhaps you browsed to the location in the code. Browsing counts as running the code. – Konrad Borowski – 2014-06-01T08:12:48.523

What if I both reinstall the system and I also change my IP? – Antonio Ragagnin – 2014-06-01T13:00:03.567

@AntonioRagagnin: It will work again. It's not that I can reliably determine things when everything is different. – Konrad Borowski – 2014-06-01T13:41:22.733

putting the logic to restrict running again counts! – ojblass – 2014-06-01T23:39:07.380

12

PHP, 22 20 chars

<?=unlink(__FILE__);

EDIT: Removed two chars at end per comments.

jay

Posted 2014-05-28T03:40:21.427

Reputation: 121

<?+space is also ok. You just cannot use a letter after the short tag. – Titus – 2017-01-17T02:56:32.400

2This can be further simplified as: <?unlink(__FILE__);, the trailing ?> is not required – leepowers – 2014-06-08T03:54:56.357

You have to start with <?= or the start tag is not recognized. – Michael Mior – 2014-06-08T12:13:44.870

2PHP destroying itself...ha! E_NOTICE line 3048 – metadings – 2014-06-08T15:46:52.067

11

Ruby,14

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

IO.write $0,$0

Mhmd

Posted 2014-05-28T03:40:21.427

Reputation: 2 019

@bfontaine Which have shebangs. This doesn't. – wizzwizz4 – 2016-05-05T15:37:28.840

@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 – 2016-05-06T07:52:46.213

@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.) – wizzwizz4 – 2016-05-06T16:06:52.677

3And what if the program is named "IO.write $0,$0"? "Assumption: Name the program something that isn't valid code in any language." – Brilliand – 2014-05-30T21:57:50.313

@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 – 2014-06-01T09:28:10.737

3@Mhmd a ruby program can end with anything. For example gem and irb are Ruby programs with no extension. – bfontaine – 2014-06-08T09:13:08.640

10

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

Justin Krejcha

Posted 2014-05-28T03:40:21.427

Reputation: 227

10

Bash 9 8 Characters

nc -l 1&

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

Falco

Posted 2014-05-28T03:40:21.427

Reputation: 261

1I 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 – 2014-05-29T21:22:48.537

nc -l 1& would fix the problem with 0 and be one byte shorter, since the last space is not needed. – kasperd – 2014-06-01T14:59:50.357

@kasperd Thanks for the input :-) – Falco – 2014-06-02T07:40:44.280

@heinrich5991 ok - than I would need 11 chars without root access to use a Port like 9654 – Falco – 2014-06-02T07:41:32.917

Care to explain why you downvoted ? – Falco – 2014-06-22T22:57:04.430

9

NodeJS - 33 bytes

require('fs').unlink(__filename);

c.P.u1

Posted 2014-05-28T03:40:21.427

Reputation: 1 049

Could you describe what this does for those who are unfamiliar with the language? – Kyle Kanos – 2014-05-30T17:38:05.560

1@KyleKanos It gets the filesystem module fs and the current filename __filename and removes that filename from the filesystem. – Keen – 2014-05-30T19:06:36.637

7You can elide the semicolon because they are optional in JavaScript. – nalply – 2014-06-01T12:07:55.473

8

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

bilde2910

Posted 2014-05-28T03:40:21.427

Reputation: 156

I ran this script, nothing happened. – Pavel – 2016-12-01T00:49:11.103

@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. – bilde2910 – 2016-12-11T22:03:49.397

1"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... – noɥʇʎԀʎzɐɹƆ – 2016-12-31T17:38:28.243

How would this be possible ? What about paging ? Process priority ? – Nicolas Barbulesco – 2014-06-03T18:17:59.947

7

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.

Isiah Meadows

Posted 2014-05-28T03:40:21.427

Reputation: 1 546

Posted after this became a popularity contest – Isiah Meadows – 2014-05-30T05:31:21.027

1The 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 – 2014-05-30T09:14:11.080

Does the file still exist afterwards? – Isiah Meadows – 2014-05-30T16:34:53.000

I now completely changed the Bash example. – Isiah Meadows – 2014-05-30T18:03:39.003

How are these not destructive? – ysap – 2014-06-05T23:05:26.523

They aren't cases of the classic fork-bomb, permanently blocking a port, running killall on Solaris (which also kills the kernel), etc. – Isiah Meadows – 2014-06-06T19:02:50.550

7

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.

kitcar2000

Posted 2014-05-28T03:40:21.427

Reputation: 2 689

6

SQL

create proc P as drop proc P

SQL Fiddle

Mikael Eriksson

Posted 2014-05-28T03:40:21.427

Reputation: 249

5

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

MD XF

Posted 2014-05-28T03:40:21.427

Reputation: 11 605

5

x86_64 NASM Assembly for Linux

This assembly program replaces itself with its source code. It essentially "decompiles" itself, replacing the binary.

SECTION .data
    source incbin __FILE__
    len equ $ - source

SECTION .text
global _start

_start:

    pop rdi           ;number of parameters
    pop rdi           ;path to executable, parameter of unlink and open

    mov    rax, 87    ;unlink
    syscall
    cmp    rax, 0
    jl     error

    mov    rax, 2     ;open
    mov    rsi, 0101o ;O_WRONLY O_CREAT
    mov    rdx, 0600o ;permissions on created file
    syscall
    cmp    rax, 0
    jl     error
    mov    rdi, rax   ;file (return value of open)

    mov    rax, 1     ;write
    mov    rsi, source
    mov    rdx, len
    syscall
    cmp    rax, 0
    jl     error

    mov    rax, 60    ;exit
    mov    rdi, 0     ;return code
    syscall

    error:
        mov    rax, 60
        mov    rdi, 1
        syscall

Compile with:

nasm -f elf64 FILENAME
ld -m elf_x86_64 FILENAME.o -o FILENAME

Or the same thing in C (with inline assembly):

#include <stdio.h>

extern char src;
asm("src: .incbin \"" __FILE__ "\"\n.byte 0");

int main(int argc, char *argv[]) {
    unlink(argv[0]);
    FILE *file = fopen(argv[0], "w");
    fprintf(file, "%s",&src);
    fclose(file);
    return 0;
}

When run, the program deletes itself, and then writes its source code to the same path as the executable was at. That way, the deleted file can always be retrieved by recompiling, even if you lost the original source code.

There must be a better way to do this in C (or maybe not), but I don't know any.

Isn't that much better than just having it delete itself!

Ian D. Scott

Posted 2014-05-28T03:40:21.427

Reputation: 1 841

1Funny way to not answer the challenge. +1 for hack value. – Stéphane Gourichon – 2016-01-09T06:34:51.903

The C version is not 64-bit specific or even architecture-specific, is it? So it is actually portable (x86 vs MIPS, ARM etc, Linux vs other OS even Windows), isn't it ? – Stéphane Gourichon – 2016-01-09T06:35:52.930

@StéphaneGourichon I think so, though I haven't tried it on anything by x86_64 linux. – Ian D. Scott – 2016-01-09T16:11:29.637

4

Ruby, 15 14

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

File.delete $0

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

onionpsy

Posted 2014-05-28T03:40:21.427

Reputation: 201

1you can save 1 character by using :File.delete $0 – Mhmd – 2014-05-28T07:45:02.630

4

PHP - 23

<?=fopen(__FILE__,'w');

user21766

Posted 2014-05-28T03:40:21.427

Reputation: 41

I wonder if it is possible to drop the semicolon here. I know it's possible with short tags like this: <?= $var ?>. – nalply – 2014-06-01T12:09:29.877

@naiply: No. ?> implies semicolon (you can even get a syntax error mentioning ;), but end of document doesn't. – Konrad Borowski – 2014-06-01T14:33:23.387

4

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.

Eduard Florinescu

Posted 2014-05-28T03:40:21.427

Reputation: 1 863

1Would you mind adding an explanation for those not that familiar with machine code? – Martin Ender – 2014-06-02T09:44:12.520

4

Coffescript

_=->_=1

compiles to:

var _;

_ = function() {
  return _ = 1;
};

zsitro

Posted 2014-05-28T03:40:21.427

Reputation: 151

3

Linux, 8 bytes

killall5

Similar to this answer, but this works on pretty much any Linux since System V and you don't need to be root. Don't believe me? Try it out on your Linux system! You'll want to save any work first...

I actually found this by accident when I was 11 messing around with Linux for the first time.

Links: killall5 manpage, recording

MD XF

Posted 2014-05-28T03:40:21.427

Reputation: 11 605

3

Commodore 64 BASIC, 7 bytes

POKE 1,3

I've had a lot of fun in various BASIC dialects POKE-ing around in the first few memory storage locations. Here's the effect of this one:

poke 1,3

Try it online! You'll have to type it in yourself.

Some other POKEs:

  • POKE 1,1 will freeze the system.
  • POKE 1,2 will clear the screen.
  • POKE 1,4 completely kills the system - the power button won't even work.
  • POKE 1,5 through POKE 1,9 do the same as POKE 1,4, but with varying levels of destruction.

MD XF

Posted 2014-05-28T03:40:21.427

Reputation: 11 605

3

Bash: 4 chars

rm a

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

Daniel

Posted 2014-05-28T03:40:21.427

Reputation: 57

1@AntonioRagagnin rm * will remove every file within the directory the source code is in. rm "$0" is a better solution. – Erik the Outgolfer – 2016-04-23T07:44:50.697

12rm * will work for every filename – Antonio Ragagnin – 2014-05-28T12:24:51.803

3@AntonioRagagnin It's better to stick to non-destructive scripts – Daniel – 2014-05-28T12:52:01.230

1rm $0 will also work for all filenames, at the cost of one character. – fNek – 2014-05-31T19:05:50.183

6@AntonioRagagnin So will rm -rf / --no-preserve-root, but better ;) – Cole Johnson – 2014-05-31T21:49:15.920

5@fNek No, it won't. Only for those without a whitespace in their name. – glglgl – 2014-05-31T21:57:17.873

@glglgl Good point. – fNek – 2014-06-01T07:56:10.363

3

Error safe termination (Python 2)

from contextlib import contextmanager
@contextmanager
def suicide():
    try:    yield
    finally:
        open(__file__    , 'w');
        open(__file__+'c', 'w');

#--------------------------------------
# Error safe code ;)
#-------------------------------------
with suicide():
    print "Goodbye cruel world!"
    jump_off_building_______crash

Simon Streicher

Posted 2014-05-28T03:40:21.427

Reputation: 131

I like how this "suicides". – Esolanging Fruit – 2017-07-09T23:39:42.463

3

(noncompetitive)

ɟ`html”Ĭ)

Try it here (Firefox only).

Translates to $('html').remove() in Javascript.

Mama Fun Roll

Posted 2014-05-28T03:40:21.427

Reputation: 7 234

What if my HTML page has no <html> element? – NoOneIsHere – 2016-06-07T20:18:57.620

ESMin runs in the online interpreter, so that shouldn't be a problem – Mama Fun Roll – 2016-06-08T16:35:55.823

3

Dyalog APL (non-competing because it is too late)

f←⎕EX'f'∘⊣

f can only be called once. It needs an argument, which is ignored:

      f←⎕EX'f'∘⊣
      f 'dummy argument'
      f 'dummy argument'
VALUE ERROR
      f'dummy argument'
     ∧

It is a so-called "atop", which is a train of two functions. The left one is applied on the result of the right one.

The right function is 'f'∘⊣ which replaces any given argument with the string 'f'.

The left function is ⎕EX, which EXpunges the object named in its argument.

The first time around, 'f'∘⊣ returns 'f', which causes ⎕EX to erase f. The second time around, calling f results in an error because f does not exist.


Here is one that can be tried online:

f←{f∘←¨}

After defining the function, the first time that it is called (with a dummy argument), e.g. f 4, the function ignores the argument, and instead redefines itself to be an operator (higher-order function). Now, operators need at least a left operand so when it is called again, the call will fail with a syntax error.

Adám

Posted 2014-05-28T03:40:21.427

Reputation: 37 779

Who said "too late" means "non-competitive"? – Erik the Outgolfer – 2016-04-23T07:54:17.943

@ΈρικΚωνσταντόπουλος Mama Fun Roll. But you did make me take a look at what I had written, and I found a typo. Thanks!

– Adám – 2016-04-25T17:27:31.873

3

AutoHotKey, 39 bytes

FileDelete %A_ScriptDir%\%A_ScriptName%

(Yes, I'm aware this is an ancient thread)

Michelfrancis Bustillos

Posted 2014-05-28T03:40:21.427

Reputation: 695

3

R, 7 Bytes

`=`=`$`

The code makes the "=" (used for assigning) become the "$" (used for subseting). After that it gives error.

Masclins

Posted 2014-05-28T03:40:21.427

Reputation: 914

I don't think this is valid. If I put it in a file I can run it as many times as I want, right? – Esolanging Fruit – 2017-07-09T23:41:02.600

1@EsolangingFruit, no on repeat execution this throws the error Error in `=` = `$` : object of type 'special' is not subsettable as validated in R version 3.4.3 (2017-11-30) – Taylor Scott – 2018-03-13T05:34:47.700

2

C, 56 chars

x[9];main(c,v)int**v;{sprintf(x,"rm %s",*v);system(x);}

Run on a UNIX system. By convention, the first string param passed to a C program is the executable name. This program simply deletes the executable (but leaves the source, which you have to recompile to run it again).

Computronium

Posted 2014-05-28T03:40:21.427

Reputation: 151

54 bytes – ceilingcat – 2019-04-01T04:08:57.963

2

TIS-100, 6 bytes

@0
HCF

The HCF (or halt and catch fire) command instantly crashes the TIS-100. The only way to run it again is to start it up again.

junkmail

Posted 2014-05-28T03:40:21.427

Reputation: 131

1Invalid, I'm afraid. From the challenge: "Any answers just initiating a reboot or halt will be disqualified." – steenbergh – 2017-11-15T16:22:54.590

2

R16K1S60 Assembly

mov [ax], ax

Simply overrides itself with with the contents of AX. the mov instruction is only one word large, so it deletes itself. Depends on AX being 0 (most releases guarentee this)

Safe version

mov [0], ax

Depends on ax not being this specific instruction

moonheart08

Posted 2014-05-28T03:40:21.427

Reputation: 693

Woah, I never thought I'd see this language here. – 12Me21 – 2018-03-13T19:45:40.447

@12Me21 Never say that around PPCG. Ever. We use everything ;) – moonheart08 – 2018-03-16T06:53:18.647

I wonder if LBPHacker will ever release the new computer he made. I'm guessing he's either really busy or he's just started over. Anyway, it might be better to use mov [0], ax since it doesn't rely on ax being 0. – 12Me21 – 2018-03-16T15:21:50.593

@12Me21 I can confirm he hasn't started over. He's just busy. Also, join #powder on freenode. – moonheart08 – 2018-03-16T20:01:12.390

I believe the instruction pointer actually points to the next memory cell, not the current one. – 12Me21 – 2018-03-16T20:17:51.803

This reminds me of a bug in the assembler where you can't have multiple 0 literals even though it technically works. (for example, mov [0],0 can be represented by 0x3000) – 12Me21 – 2018-03-16T20:40:11.407

2

Plain TeX - 31 (24) chars

\openout1=\jobname\write1{}\bye

If you save it as file a.tex then:

\openout1=a\write1{}\bye

yo'

Posted 2014-05-28T03:40:21.427

Reputation: 563

2

Bash

This deletes the file and makes sure that you can't recover it. So it definitely can't execute more than once.

shred "$0"

shred is a program to securely delete files by overwriting them. It's in coreutils.

user16402

Posted 2014-05-28T03:40:21.427

Reputation:

2

JAVASCRIPT (35 26 bytes when minified, in case that matters.) I know this is a late entry, but I had a situation where I considered being able to kill a function and decided it'd make a good entry here. (Still not sure if I'll actually use it.)

funny = function(){
  alert(0);
  window.funny = '';
};

funny();
funny();

minified

a=function(){alert(0);window.a=""};

Alert isn't really needed

a=function(){window.a=""};

TecBrat

Posted 2014-05-28T03:40:21.427

Reputation: 222

Just do function a(){a=0} – minmaxavg – 2016-03-30T22:05:23.393

2

Python 2.7

import inspect
import os
for x in range(0, 2):
    os.remove(inspect.stack()[0][1])
    print "am I dead yet?"

It only runs 1/2 of a time.

Ephraim

Posted 2014-05-28T03:40:21.427

Reputation: 143

1

8602/8610 machine code, 4 bytes

assuming that the program is stored at address $0800

78 4C 00 08

breakdown to assembler:

START    sei        // disable interupts
         jmp START  // endless loop

C64 machine code, 3 bytes

4C E2 FC

this jumps to the builtin reset routine of the C64 (which, among other actions, clears the RAM)

run with SYS <address>

Titus

Posted 2014-05-28T03:40:21.427

Reputation: 13 814

1This should be two different answers. – MD XF – 2017-05-30T16:25:57.167

1

OSI Challenger 1P

POKE 3,3

There are lots of BASIC answers because BASIC made the mistake of allowing users to directly access all memory. But this is the shortest POKE command yet. If only it was ...

You can try this here - scroll down, hit Run, hit C to cold-boot, then Enter-Enter to get into BASIC mode. Then type POKE 3,3 and watch the PC burn.

MD XF

Posted 2014-05-28T03:40:21.427

Reputation: 11 605

1

Braingolf Inline Interpreter, 28 bytes [non-competing]

'''
open(__file__,'w')
a='''

Braingolf's Inline Interpreter treats the braingolf code as simply a multiline string within the Python3 interpreter.

This allows what is effectively an injection attack, where you can end the multiline string with three single quotes, then insert python code. The code will only run if you then begin a new multiline quote at the end, however.

Skidsdev

Posted 2014-05-28T03:40:21.427

Reputation: 9 656

1You don't have to add non-competing (that rule was removed). – Esolanging Fruit – 2017-07-09T23:36:59.820

Also, doesn't this wipe the interpreter file, and not the program file? – Esolanging Fruit – 2017-07-09T23:37:24.300

1

MOO, 24 bytes

delete_verb(this, verb);

Requires that this code is run as an actual verb, rather than through eval (or $code_utils:eval_d).

pppery

Posted 2014-05-28T03:40:21.427

Reputation: 3 987

1

JS, 8B

a=b=>a=0

calling a means a=0, thus a can't be called 2×.

user75200

Posted 2014-05-28T03:40:21.427

Reputation: 141

1

SmileBASIC

@memory_leak
If shift("this") then @memory_leak

There is a bug where using POP() or SHIFT() on a string literal causes a memory leak, and eventually there will not be enough memory left for the program to run. Trying to run it again will cause an error before the program starts.

IF ... THEN @LABEL is a shortcut for IF ... THEN GOTO @LABEL.

12Me21

Posted 2014-05-28T03:40:21.427

Reputation: 6 110

Oh cool to see that its If ... Then @Label in SmileBASIC - it is If ... GoTo Label In the VB family – Taylor Scott – 2018-03-13T05:36:56.317

1SmileBASIC actually supports both forms, for some reason. (I think I had forgotten about it when I wrote this answer) – 12Me21 – 2018-03-13T17:17:18.300

1

oldschool DOS


You don't even need a compiler or interpreter, just the prompt. Not even reboot will let it run again once it completes (note: do not try on something you don't want to sacrifice. OS likely won't boot either.)

deltree C:\

liljoshu

Posted 2014-05-28T03:40:21.427

Reputation: 131

1

Windows batch, 4 bytes

.>%0

This will attempt to execute '.' as a command, while redirecting stdout to the original file, resulting in destruction of the original file.

peter ferrie

Posted 2014-05-28T03:40:21.427

Reputation: 804

1

Python 24

Name the file 'q'

import os
os.remove("q")

Harry Beadle

Posted 2014-05-28T03:40:21.427

Reputation: 787

3try os.remove(__file__) instead. – Erik the Outgolfer – 2016-04-23T07:50:26.147

1

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

gxtaillon

Posted 2014-05-28T03:40:21.427

Reputation: 577

It's now a popularity contest. – Isiah Meadows – 2014-05-30T05:41:08.593

1

Bash: 2 chars

>a

Using inspiration from a couple of the other solutions, I came up with this solution in only two chars. Put this in a script called a and run it.

Just like the posts I got inspired by, this relies on the calling shell working around the missing #! line. Relying on this workaround is absolutely necessary, since you can't even produce a valid #! line in that space.

This happens if you let the kernel call it without a shell to work around the missing #! line:

$ strace ./a
execve("./a", ["./a"], [/* 47 vars */]) = -1 ENOEXEC (Exec format error)

kasperd

Posted 2014-05-28T03:40:21.427

Reputation: 829

This script does nothing when I run it. I can run it several times. – Nicolas Barbulesco – 2014-06-03T18:21:05.437

@NicolasBarbulesco Make sure you run it from the directory where it is located. The contents of the script will be gone after the first run, there won't be anything left to run the second time around. – kasperd – 2014-06-03T18:34:22.470

The second run shows nothing, like the first run, so I did not see what happened. In fact, the first run erases the script's content. How is this achieved ? – Nicolas Barbulesco – 2014-06-07T13:09:55.690

2@NicolasBarbulesco > redirects the output of the command on that line to a file. The file name to redirect the output to is a. So the script runs an empty command, and the output of that empty command is written to the file a, which is the script itself. – kasperd – 2014-06-07T13:55:51.427

OK, it is simple in fact ! – Nicolas Barbulesco – 2014-06-07T18:06:26.757

2@NicolasBarbulesco It is easier to fit something simple into two bytes than to fit something complicated into two bytes. – kasperd – 2014-06-07T18:19:51.930

1

Shell script (Linux Bash); 4 characters

rm *

Warning ! Don’t try this at home.

This shell script can be run only once. When run, this shell script will self-destruct.

Nicolas Barbulesco

Posted 2014-05-28T03:40:21.427

Reputation: 249

2This implicitly assumes that the process' "current directory" matches the script directory. The "run once" property will fail in other cases. Example: say script is in ~/a, current directory is ~/b. The script can be run with ../a/thescript and it will only try to delete in ~/b which won't delete the script (it's not in that directory). b may even be already empty before the script runs. – Stéphane Gourichon – 2016-01-09T06:31:10.367

1For non-bash users: * is a glob, which expands to a list of all the files in the current directory. so it will delete everything in the folder the script is in as well as itself – None – 2014-06-09T19:26:56.817

1

PowerShell (37)

Save following code to a script file (test.ps1)

rm $MyInvocation.MyCommand.Definition

Run from command line:

PS > .\test.ps1

Script will automatically delete itself.

microbian

Posted 2014-05-28T03:40:21.427

Reputation: 2 297

1

AppleScript ; 17 chars

delete document 1

I was playing with more elegant solutions like this one :

set the contents of the front document to ""

But the action of delete document 1 is even more fun !

Nicolas Barbulesco

Posted 2014-05-28T03:40:21.427

Reputation: 249

you know the is optional? so you can just write set contents of front document to "" – dkudriavtsev – 2016-10-10T19:51:26.630

1

beeswax, 12 bytes

_8F+++P]f1Fw

Save this program under the name ! and execute it.

              lstack                       gstack
_             [0,0,0]•                                          create bee
 8            [0,0,8]•                                          lstack 1st=8
  F           [8,8,8]•                                          all lstack=lstack 1st
   +++        [8,8,16]•                                         1st=1st+2nd
              [8,8,24]•                                         3 times
              [8,8,32]•
      P       [8,8,33]•                                         increment 1st
       ]      [8,8,2377900603251621888]•                        rotate bits of 1st by 2nd steps
        f                               [2377900603251621888]•  push lstack 1st ont gstack
         1    [8,8,1]•                                          lstack 1st=1
          F   [1,1,1]•                                          all lstack=lstack 1st
           w            write gstack to file. lstack 1st=bytes used for file name, lstack 2nd= used file content bytes.

If we look at the stack contents in hex, it gets clearer what’s happening:

lstack[8,8,33]• is lstack[0x0000000000000008,0x000000000000008,0x0000000000000021]• in hex.

If we rotate the bits of the 1st lstack value by 8 to the right, we get

lstack[8,8,2377900603251621888]•, which is

lstack[0x0000000000000008,0x000000000000008,0x2100000000000000]• in hex.

Instruction f pushes the 1st lstack value on the gstack:

gstack[0x2100000000000000]•

Now comes instruction w: First, the 4-byte words of the gstack get reinterpreted as a stack of UInt8 values:

[0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x21]•, in little endian order. The MSB is on top of the stack.

Instruction w takes the 1st lstack value as number of bytes taken for the file name, and the 2nd lstack value gives the number of bytes stored in the file. lstack[1,1,1]• means that 1 byte is taken as file name. 0x21 is the ASCII code for !, which is the name of the program itself. The next single byte (lstack 2nd), the value 0x00 is stored as file content, which is not executable as beeswax program.

M L

Posted 2014-05-28T03:40:21.427

Reputation: 2 865

1

Caché ObjectScript, 12 bytes

k ^rOBJ($zn)

Output:

SAMPLES>do ^test

SAMPLES>do ^test

DO ^test
^
<NOROUTINE> *test

adaptun

Posted 2014-05-28T03:40:21.427

Reputation: 161

1

q (14 bytes)

This program deletes itself when run.

hdel hsym .z.f

skeevey

Posted 2014-05-28T03:40:21.427

Reputation: 4 139

1

Bash (7 characters)

TMOUT=1

It destroying the user session within a second by terminating the shell. See: man bash.

Example:

$ TMOUT=1
timed out waiting for input: auto-logout
Saving session...completed.

[Process completed]

kenorb

Posted 2014-05-28T03:40:21.427

Reputation: 398

That's not really different from typing exit or ^D. The later key combination will send EOF to the shell making it 0 bytes. – kasperd – 2016-11-07T16:19:14.697

0

Z80 ASM on TI-83/84 series

AsmPrgm
C3FFFF

If you put this into a TI-83 or 84 (any version, except 84+CE and CSE), the calculator will completely reset itself. Everything in RAM will be reset, including the program at hand.

For the TI84+CSE:

Asm84CPrgm
C3FFFF

Disclaimer: This might not work if you are running any apps that change the functionality of your calculator significantly. (i.e. libraries, non-official OS's)

Élektra

Posted 2014-05-28T03:40:21.427

Reputation: 284

0

AutoIt - 27 bytes

Truncs itself to 0:

FileOpen(@ScriptFullPath,2)

mınxomaτ

Posted 2014-05-28T03:40:21.427

Reputation: 7 398

0

Batch (This isn't code golf)

echo "">%0.bat

Assumes you call it without the extension. If you are calling it with the extension, use echo "">%0.

SuperJedi224

Posted 2014-05-28T03:40:21.427

Reputation: 11 342

0

Vitsy, 8 bytes (I know it isn't Golf but I like to be concise)

iG" mr",
iG        Push name of self.
  " mr"   Push "rm " in front of it.
       ,  Execute as shell.

This assumes you run on a computer with rm as a command for delete. For an environment with del as its command for delete, it's 9 bytes (I think, I can't really test it):

iG" led",
iG        Push name of self.
  " led"  Push "del " in front of it.
        , Execute as shell.

It basically just deletes itself. :P

Addison Crump

Posted 2014-05-28T03:40:21.427

Reputation: 10 763

-1

tcl, 7 bytes

vwait v

Explanation

sergiol

Posted 2014-05-28T03:40:21.427

Reputation: 3 055

1

The same answer I gave on http://codegolf.stackexchange.com/a/105812/29325

– sergiol – 2017-01-17T00:35:45.177

@ojblass: why the downvote? – sergiol – 2018-05-02T13:24:00.743

-3

Bash file linux

#!/bin/bash
shutdown -h now

Abhishek Mishra

Posted 2014-05-28T03:40:21.427

Reputation: 95

1Welcome to the site! I do believe that shutdown requires root access (It does when I test it) which is forbidden by the challenge. – Post Rock Garf Hunter – 2018-03-13T05:52:09.583