Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Imagine I have a script foo. It should be run once when the user logs in and isn't needed after a successful run.

My question: Is it safe to remove the script file from within the script?



# do something

# if successful
rm /path/to/foo
exit 0
share|improve this question
Not entirely unrelated, you could use #!/bin/bash -e to ensure that the script file is removed only if nothing goes wrong. –  sr_ Feb 29 '12 at 10:30
Yes, it is safe. If you want to know, why, read stackoverflow.com/questions/2028874/… –  jofel Feb 29 '12 at 10:34
@jofel Sounds good, I suggest you make this an answer. :-) –  htorque Feb 29 '12 at 10:52
@sr_ Thanks for the hint! –  htorque Feb 29 '12 at 10:52
If in doubt you can replace the last two lines with exec rm /path/to/foo. –  kasperd May 31 at 22:03

2 Answers 2

up vote 5 down vote accepted

It it safe to remove the shell file while running it, since file handlers are not affected by (re)moving the corresponding file.

For more information, see here.

share|improve this answer
Just be aware that it might not work, depending on your system (ie the rm <it-self> will not succeed on HP-Ux. –  Ouki Feb 29 '12 at 12:02
@Ouki, why? Wouldn't that violate POSIX? –  maxschlepzig Feb 29 '12 at 17:59
@maxschlepzig POSIX allows the deletion of the last link to an executable that is currently being executed to fail: unlink may fail with ETXTBUSY. (Oddly, “pure procedure” and “shared text” aren't defined in the spec; AFAIK they mean a component of an executable program: the executable itself or a library it uses). All major unices other than HP-UX allow executables to be renamed and unlinked. –  Gilles Feb 29 '12 at 19:49
@Ouki That should be easy to get around by simply ending the script with exec rm /path/to/foo. –  kasperd May 31 at 22:02

I was always nervous about this so I did:

(sleep 5; rm /path/to/shell/script) &
exit 0

Alternately you can chain to a temporary script:

echo >/tmp/rmme rm /path/to/shell/script
. /tmp/rmme
share|improve this answer
In both of your suggested approaches there will still be a shell process which has not finished executing the script by the time it is deleted. –  kasperd May 31 at 21:57

Your Answer


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

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