88

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

SCRIPT_PATH=${0%/*}
if [ "$0" != "$SCRIPT_PATH" ] && [ "$SCRIPT_PATH" != "" ]; then 
    cd $SCRIPT_PATH
fi

What does the ${0%/*} stand for? Thanks

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
user785099
  • 5,323
  • 10
  • 44
  • 62

1 Answers1

137

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
mic4ael
  • 7,974
  • 3
  • 29
  • 42
c00kiemon5ter
  • 16,994
  • 7
  • 46
  • 48
  • 3
    so, it's aa the `dirname($0)` – clt60 Jun 18 '11 at 13:43
  • 9
    in this script, yes, it works like `dirname "$0"` but it could cause problems. If you called the script like this: `bash script` then `${0/*}` doesn't give you the path, it returns the scriptname, or if you specified full path (_/path/to/script_) it returns nothing, so it's not guaranteed to work as expected in all situations. – c00kiemon5ter Jun 18 '11 at 13:54
  • I was busy typing a question on superuser about a line that has this, I wrote in my question that I'd usually type parts of the code into google to get a result but seemingly I forgot that but as soon as I broke up my question and analysed it before posting, I googled just `${0%}` and landed here, you have made it clear for me :) – SidOfc Dec 10 '15 at 10:43
  • 1
    See also "Get the source directory of a Bash script from within the script itself" https://stackoverflow.com/questions/59895/get-the-source-directory-of-a-bash-script-from-within-the-script-itself – MarcH Nov 22 '19 at 17:55
  • `echo ${var%%/*}` --> `foo` – Pau Coma Ramirez Dec 21 '22 at 20:45