Change to the Directory of the Script
suggest changeIn general, there are two types of Bash scripts:
- System tools which operate from the current working directory
- Project tools which modify files relative to their own place in the file system
For the second type of scripts, it is useful to change to the directory where the script is stored. This can be done with the following command:
cd "$(dirname "$(readlink -f "$0")")"
readlink -f here is the GNU version. BSD readlink (the default on macOS) does not support -f.
This command runs 3 commands:
readlink -f "$0"determines the path to the current script ($0)dirnameconverts the path to the script to the path to its directorycdchanges the current working directory to the directory it receives fromdirname
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents