2

Can anyone please explain what the following bash command does?

CMD_PATH=${0%/*}

What is the value assigned to the CMD_PATH variable?

Vombat
  • 1,156
  • 1
  • 15
  • 27
  • Also see http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in – devnull Jun 26 '13 at 12:07

3 Answers3

4

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.

l0b0
  • 55,365
  • 30
  • 138
  • 223
rr-
  • 14,303
  • 6
  • 45
  • 67
2

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
fedorqui
  • 275,237
  • 103
  • 548
  • 598
1

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
    
Adam Siemion
  • 15,569
  • 7
  • 58
  • 92