I encountered a git commit which cleans up some readlink
and dirname
command with this magic variable substitution cd ${0%/*}
.
How does bash interpret it?
${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.
If the $0 special variable is used within a Bash script, it can be used to print its name and if it is used directly within the terminal, it can be used to display the name of the current shell.
$* expands to all parameters that were passed to that shell script. $0 = shell script's name. $1 = first argument. $2 = second argument ...etc. $# = number of arguments passed to shellscript.
- 1 means the first parameter passed to the function ( $1 or ${1} ) - # means the index of $1 , which, since $1 is an associative array, makes # the keys of $1.
The command cd ${0%/*}
changes directory to the directory containing the script, assuming that $0
is set to the fully-qualified path of the script.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With