Hacker News new | ask | show | jobs
by nodesocket 4172 days ago
What is this magic doing?

   $(cd "${0%/*}")
4 comments

$0 is the path of the script. ${0%/* } takes $0, deletes the smallest substring matching /* from the right (the filename) and returns the rest, which would be the directory of the script. So this changes the directory to the directory the script is located in.
$0 is not the path of the script. $0 is the path passed to the shell used to execute the script. If run via the #! line, it will contain a path of some kind. But if it's passed directly using "bash myscript.sh", then it won't.

And yes, dirname is a way out of this. I'd do this:

    "$(cd "$(dirname "$0")"; pwd)"
if I wanted the path to the script. I would also sanity-check the path by testing for the existence of some files or directories that are expected to exist under it, before trying to delete it all.
Is there any good reason to use this approach over the more readable 'dirname $0'? Not that it would have made any difference to the bug in question of course.
Per a subsequent comment in the github thread:

"the ${0%/*} pulls the path out of $0, cd's into the specified directory, then uses $PWD to figure out where that directory lives - and all this in a subshell, so we don't affect $PWD"

So for example, that would take /user/amputect/seam_setup.sh and change directories into into /user/amputect.

Assuming the shell script is for Bash, that incantation removes the shortest matching suffix which matches the pattern "/*". So it is attempting to remove the filename component from a pathname string in the "0" positional parameter.

Since $0 is usually the name of the shellscript itself, this would be trying to obtain the directory path of the shellscript.

It's a bashism. Open up "man bash" and search for "Remove matching suffix pattern".
which, regrettably, is not something you can do with `man` if you find `${0%/*}` in a script you're reading that someone else wrote.
No, but you can find it by searching for "%", because that's exactly what I did.