Can anyone please explain what the following bash command does?
CMD_PATH=${0%/*}
What is the value assigned to the CMD_PATH variable?
It strips anything beyond last occurence of slash character from $0
variable, which is (in most cases, sometimes depending on how the script is run) the folder the script is currently executed from.
It shows the first directory on the working running process. If it is in a script, it shows its name.
From What exactly does "echo $0" return:
$0 is the name of the running process. If you use it inside a shell, then it will return the name of the shell. If you use it inside a script, it will be the name of the script.
Let's explain it:
$ echo $0
/bin/bash
is the same as
$ echo ${0}
/bin/bash
Then a bash substitution is done: get text up to last slash:
$ echo ${0%/*}
/bin
This substitution can be understood with this example:
$ a="hello my name is me"
$ echo ${a% *}
hello my name is
Returns the name of the directory from which the currently running script has been started.
To test it:
create directory /tmp/test
:
mkdir /tmp/test
create file 't.sh` with such content:
#!/bin/bash
echo $0
echo ${0%/*}
give t.sh
execution permission:
chmod +x /tmp/test/t.sh
execute it and you will see:
/tmp/test/s.sh
/tmp/test