2

Can anyone please explain what the following bash command does?

CMD_PATH=${0%/*}

What is the value assigned to the CMD_PATH variable?

1

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Sure, did not check properly. See my updated answer, @anubhava
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
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.