Shells come with a magic variable $0 for performing various operations. We can use these to perform certain functions. In its simplest incantation we can just echo out $0 to get the path a script is in from within the script:
echo $0
We can also just get the directory a script is in. For example, if we want to see if it’s being executed from within an app bundle, temp, or download directory. This is also helpful if we’ve created files in a folder we created and need to delete them all at the end of a larger atomic operation (e.g. rm -r …/<the directory name>. To do that we’ll use surname and readlink (each alone can have different results according to the working directory of a shell that a script is invoked from):
dirname -- "$( readlink -f -- "$0"; )";
We can also remove the script from within the script at the end using rm, a simple way to just erase ourselves when we’re done with the totally not-shady thing we just did:
rm -- "$0"