11

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?

E.g.:

#!/bin/bash

# do something
...

# if successful
rm /path/to/foo
exit 0
4
  • 2
    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, 2012 at 10:30
  • 4
    Yes, it is safe. If you want to know, why, read stackoverflow.com/questions/2028874/…
    – jofel
    Feb 29, 2012 at 10:34
  • 2
    @jofel Sounds good, I suggest you make this an answer. :-)
    – htorque
    Feb 29, 2012 at 10:52
  • If in doubt you can replace the last two lines with exec rm /path/to/foo.
    – kasperd
    May 31, 2015 at 22:03

2 Answers 2

6

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.

4
  • 2
    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, 2012 at 12:02
  • 1
    @Ouki, why? Wouldn't that violate POSIX? Feb 29, 2012 at 17:59
  • 3
    @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. Feb 29, 2012 at 19:49
  • 3
    @Ouki That should be easy to get around by simply ending the script with exec rm /path/to/foo.
    – kasperd
    May 31, 2015 at 22:02
0

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
2
  • 1
    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, 2015 at 21:57
  • What you want to do is exec rm /path/to/shell/script
    – osvein
    Apr 18, 2020 at 11:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .