"$ {0% / *}" and "$ {0 ## * /}" in sh

These are excerpts from the brew team.

BREW_FILE_DIRECTORY=$(chdir "${0%/*}" && pwd -P)
export HOMEBREW_BREW_FILE="$BREW_FILE_DIRECTORY/${0##*/}"

What is the meaning ${0%/*}and ${0##*/}in the shell?

+5
source share
2 answers

This is a shell for expanding parameters :

  • ${var%/*}- delete everything after the last entry /.
  • ${var##*/}- delete everything until the last occurrence /.

Since you are in a script, it $0refers to the name of the script itself.

Together, this returns either the path or the name of the script used. So what do you do:

BREW_FILE_DIRECTORY=$(chdir <path_of_script> && pwd -P)
export HOMEBREW_BREW_FILE="$BREW_FILE_DIRECTORY/<script_name>"

Test

$ r="hello/how/are/you"
$ echo ${r%/*}
hello/how/are
$ echo ${r##*/}
you

From the above link (edited versions to make them shorter):

$ {parameter ## word}

, . , ( ##) . '@' *, , - .

${% }

, . , ( "% case" ). '@' *, , - .

$0, . Bash β†’ 6.1 bash:

, -c, -s, , (. ). Bash , $0 , . Bash , .

+8

.

${string%substring}  # Deletes shortest match of $substring from back of $string.
${string##substring} # Deletes longest match of $substring from front of $string.

, , .

${0%/*}

, $0 , , . , dirname.

${0##*/}

, $0 , . , basename.

+3

All Articles