Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

scripting

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

like image 672
user785099 Avatar asked Jun 18 '11 02:06

user785099


People also ask

What is ${ 0 * in bash?

${0} is the first argument of the script, i.e. the script name or path. If you launch your script as path/to/script.sh , then ${0} will be exactly that string: path/to/script.sh . The %/* part modifies the value of ${0} . It means: take all characters until / followed by a file name.

What does * represent in bash?

It's a space separated string of all arguments. For example, if $1 is "hello" and $2 is "world", then $* is "hello world".

What does * mean in shell script?

It means all the arguments passed to the script or function, split by word.

What does ${ 1 mean in bash script?

* (Bash's syntax is super consistent, and not at all confusing) This is a pattern match on the value of the first argument ( ${1} ) of your function or script. Its syntax is ${variable#glob} where. variable is any bash variable.


1 Answers

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 
like image 177
c00kiemon5ter Avatar answered Oct 20 '22 09:10

c00kiemon5ter