[Question]
  [
**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.
  
[Answer]
## [Vigil](https://github.com/munificent/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
```
[Answer]
# 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](http://en.wikipedia.org/wiki/Shebang_%28Unix%29). 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`.
[Answer]
# 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](http://en.wikipedia.org/wiki/Pentium_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.
[Answer]
# Bash, 5
```
>"$0"
```
Truncates itself to zero length.
If the filename doesn't contain spaces, `>$0` works for **3 chars**!
[Answer]
# 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.
[Answer]
# 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 [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") question before it got changed to [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'")):
```
chmod -x "$0"
```
## Sneaky version by Łukasz Niemier
```
#!/bin/chmod 0
```
[Answer]
# 6800 machine code - 1 byte
```
0xDD
```
This is known as HCF or [Halt and Catch Fire](http://en.wikipedia.org/wiki/Halt_and_Catch_Fire#Motorola_6800)
[Answer]
# 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
```
[Answer]
## Commodore 64 BASIC
This one doesn't delete the program.
```
1 POKE 2048,1
```
![Self-destruct](https://i.stack.imgur.com/IAqIJ.png)
According to the [Commodore 64 memory map](http://sta.c64.org/cbm64mem.html), address`2048`is unused, but it must contain a value of `0` so that the BASIC program can be RUN.
[Answer]
Assumption: Running Solaris, logged in as root
```
killall
```
[Answer]
# 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 ;)
[Answer]
# Python, 18
```
open(__file__,'w')
```
Truncates the file by opening it in write-only mode.
[Answer]
# 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
```
[Answer]
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.
[Answer]
## Bash , 12
**Note: This is destructive.**
```
:(){ :|:&};:
```
It's the popular bash fork-bomb. It exponentially eats all memory and PID's locking up the system. A hard-reboot will allow the code to be run again though why would you want to do that?
---
## Bash , 10
```
:(){ :&};:
```
For two less chars, this eats your memory linearly.
---
## Bash , 7
```
w;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`
[Answer]
## Commodore 64 BASIC
```
0 NEW
```
[`NEW`](http://www.c64-wiki.com/index.php/NEW) deletes the program.
[Answer]
## 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"
});
```
[Answer]
## 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})
```
[Answer]
## Bash (5)
```
rm $0
```
Assuming you don't have spaces in the filename.
[Answer]
## 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;
}
```
[Answer]
# 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](https://www.heroku.com/policy/privacy) if you like. I don't check the data stored in a database, it's stored purely to allow the code to execute once.
[Answer]
# **PHP, ~~22~~ 20 chars**
```
<?=unlink(__FILE__);
```
EDIT: Removed two chars at end per comments.
[Answer]
# [GW-BASIC](//en.wikipedia.org/wiki/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](https://i.stack.imgur.com/zhPCc.gif)](https://i.stack.imgur.com/zhPCc.gif)
[Answer]
# Ruby,14
It rewrites the source code as the name of the program.
```
IO.write $0,$0
```
[Answer]
**NodeJS - 33 bytes**
```
require('fs').unlink(__filename);
```
[Answer]
## Bash 9 8 Characters
```
nc -l 1&
```
Will only run once, because the port is blocked forever.
[Answer]
# 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
```
[Answer]
## 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>
[Answer]
# 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.
[Answer]
# 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!
]