Variables π
$0 stands for the name of the script
$# - number of arguments passed in
$$ - pid (process id) of this command
$1 (up to $9) - the first (ninth) element in a collection
$@ - all the arguments
$? β error code from the previous command, e.g.
To add to this already thorough list, $* creates one combined argument separated by the $IFS character (default is a space), while $@ acts like an array of each individual argument (which, as you mention, can be isolated further by accessing them in order from $1 to $9, but also beyond that by adding braces ${10}, ${11} ...).
# testvar for i in"$@";do echo"@ '$i'";done
for i in"$*";do echo"* '$i'";done
Would print the following with multiple arguments:
./testvar foo bar baz 'long arg'
@ 'foo'
@ 'bar'
@ 'baz'
@ 'long arg'*'foo bar baz long arg'
So if youβre trying to iterate over arguments individually, use $@, whereas if youβre trying to do something with the group of arguments as a single whole, use $*.
Ohhhh, this is super interesting and helpful. Thank you for taking the time to write the comment and for sharing the link - Iβm going to check it out!
My pleasure! Bash can be really obtuse sometimes, but it's a powerful command language, and you can especially do a lot with these positional parameter arguments depending on how you set up your scripts. Happy hacking!
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Awesome write-up! Iβve been knee deep in bashβs positional parameters all week.
To add to this already thorough list,
$*
creates one combined argument separated by the$IFS
character (default is a space), while$@
acts like an array of each individual argument (which, as you mention, can be isolated further by accessing them in order from$1
to$9
, but also beyond that by adding braces${10}, ${11} ...
).For example (taken from here):
Would print the following with multiple arguments:
So if youβre trying to iterate over arguments individually, use
$@
, whereas if youβre trying to do something with the group of arguments as a single whole, use$*
.Ohhhh, this is super interesting and helpful. Thank you for taking the time to write the comment and for sharing the link - Iβm going to check it out!
My pleasure! Bash can be really obtuse sometimes, but it's a powerful command language, and you can especially do a lot with these positional parameter arguments depending on how you set up your scripts. Happy hacking!