DEV Community

Discussion on: Set cwd to script directory

Collapse
 
kogans profile image
Stanislav Kogan

In this specific case, you are correct.
My comment was more of a general nature.

Thread Thread
 
adamkdean profile image
Adam K Dean

Oh absolutely. Using cd in a script is general not recommended due to the very nature of relative paths. If you don't know where you are, how can you know where to go? Like when you drop out of hyperspace unexpectedly, if you don't know where you are, you can't get home!

The beauty of the snippet above cd "${0%/*}" is ${0%/*} which takes the filename of the script, e.g. /home/bin/script.sh and discards everything after the last slash to give you the path, which you change directory into.

Which means you can negate not knowing where you executed the script from, and suddenly, you're able to use relative paths, such as the implicit relative Dockerfile expected by docker build.