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?
${0}
is the first argument of the script, i.e. the script name or path. If you launch your script aspath/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 bepath/to
.You can see it in action on your shell:
Sh supports many other kinds of "parameter substitution". Here is, for example, how to take the file name instead of the path:
In general,
%
and%%
strip suffixes, while#
and##
strip prefixes. You can read more about parameter substitution.