What is the meaning of ${0%/*} in a bash script?

前端 未结 1 573
情歌与酒
情歌与酒 2020-12-12 23:16

I am trying to understand a test script, which includes the following segment:

SCRIPT_PATH=${0%/*}
if [ \"$0\" != \"$SCRIPT_PATH\" ] && [ \"$SCRIPT_P         


        
相关标签:
1条回答
  • 2020-12-12 23:58

    It is called Parameter Expansion. Take a look at this page and the rest of the site.

    What ${0%/*} does is, it expands the value contained within the argument 0 (which is the path that called the script) after removing the string /* suffix from the end of it.

    So, $0 is the same as ${0} which is like any other argument, eg. $1 which you can write as ${1}. As I said $0 is special, as it's not a real argument, it's always there and represents name of script. Parameter Expansion works within the { } -- curly braces, and % is one type of Parameter Expansion.

    %/* matches the last occurrence of / and removes anything (* means anything) after that character. Take a look at this simple example:

    $ var="foo/bar/baz"
    $ echo "$var"
    foo/bar/baz
    $ echo "${var}"
    foo/bar/baz
    $ echo "${var%/*}"
    foo/bar
    
    0 讨论(0)
提交回复
热议问题