Ubuntu – What does ${0%/*} in shell scripts do

command linesh

Sorry if this is a stupid question, but I searched about it without success.

What does exactly the second line do ?:

#!/bin/sh
cd ${0%/*} || exit 1

I know the first is the shebang, the second tries to change directory but the confusing part is ${0%/*}.

Can you please explain me that second line?

Best Answer

${0} is the first argument of the script, i.e. the script name or path. If you launch your script as path/to/script.sh, then ${0} will be exactly that string: path/to/script.sh.

The %/* part modifies the value of ${0}. It means: take all characters until / followed by a file name. In the example above, ${0%/*} will be path/to.

You can see it in action on your shell:

$ x=path/to/script.sh
$ echo "${x%/*}"
path/to

Sh supports many other kinds of "parameter substitution". Here is, for example, how to take the file name instead of the path:

$ echo "${x##*/}"
script.sh

In general, % and %% strip suffixes, while # and ## strip prefixes. You can read more about parameter substitution.

Related Question