DEV Community

Discussion on: Set cwd to script directory

Collapse
 
kogans profile image
Stanislav Kogan

Generally, it is a good idea to avoid "cd" in scripts. The problem is, that there is no guarantee that the directory will still be there after you cd'ed into it. Be a Jedi and use absolute paths unless you have no choice.

Collapse
 
adamkdean profile image
Adam K Dean

The above takes that into account, and sets the path to the location of the script at runtime. Simply, it negates the above risk without requiring the rigidity of absolute paths.

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.