0

I want to make a file that runs a script, then deletes itself. I know that its root would most likely be "~/Library/Downloads/filename.app". How would I go about having it self destruct? I'm working in script editor.

  • It's a bit confusing why you would want such a script. If you want it to delete itself after running, why not just type the commands and avoid the whole creating then deleting the file part? – l0b0 Aug 23 '19 at 07:09

1 Answers1

0

I'm not sure if I understand correctly as shell script would traditionally have .sh suffix instead of .app one (if any) and I'm not familiar with anything that I'd call "script editor", but alas here's my solution.

If you are in bash environment, you can make use of the BASH_SOURCE array. Provided that you didn't change the current working directory, you can directly call

rm "${BASH_SOURCE[0]}"

(or just rm "$BASH_SOURCE").

If you are using cd or make larger script, it might be advisable to save fully resolved path to the script at the beginning and remove that file at the end (not somewhere in the middle as running bash scripts are NOT independent on their source files*) like so:

#!/bin/bash
self=$(realpath "${BASH_SOURCE[0]}")

#
# code so ugly I want to delete it when I'm done
#

rm "$self"

*Edit shell script while it's running

veprolet
  • 361
  • 2
  • 12
  • (BTW, I'd argue that a shell script *shouldn't have any suffix at all*; `.sh` is appropriate for shell libraries or fragments intended to be sourced rather than executed; *scripts* with `+x` bits and shebangs are executables, and just as you run `/bin/ls` instead of `/bin/ls.elf`, executables on UNIX don't conventionally have extensions -- see http://www.talisman.org/~erlkonig/documents/commandname-extensions-considered-harmful/ for a longer screed on the topic, or http://wooledge.org/~greybot/meta/.sh for the history of the irc.freenode.org #bash factoid on the subject). – Charles Duffy Aug 22 '19 at 20:18