DEV Community

Discussion on: Shell tools and scripting β€” missing semester notes

Collapse
 
timmybytes profile image
Timothy Merritt

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.

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):

# testvar 
for i in "$@"; do echo "@ '$i'"; done
for i in "$*"; do echo "* '$i'"; done
Enter fullscreen mode Exit fullscreen mode

Would print the following with multiple arguments:

./testvar foo bar baz 'long arg'
@ 'foo'
@ 'bar'
@ 'baz'
@ 'long arg'
* 'foo bar baz long arg'
Enter fullscreen mode Exit fullscreen mode

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 $*.

Collapse
 
sylwiavargas profile image
Sylwia Vargas

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!

Collapse
 
timmybytes profile image
Timothy Merritt

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!