What does $# mean in shell?
I have code such as
if [ $# -eq 0 ] then
I want to understand what $# means, but Google search is very bad for searching these kinds of things.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can always check the man page of your shell. man bash says:
Special Parameters # Expands to the number of positional parameters in decimal.
Therefore a shell script can check how many parameters are given with code like this:
if [ "$#" -eq 0 ]; then echo "you did not pass any parameter" fi
Method 2
Actually,
`$` refer to `value of` and `#` refer to `number of / total number`
So together
`$#` refer to `The value of the total number of command line arguments passed.`
Thus, you can use $# to check the number of arguments/parameters passed like you did and handle any unexpected situations.
Similarly, we have
`$1` for `value of 1st argument passed` `$2` for 'value of 2nd argument passed`
etc.
Method 3
That is
- the number of parameters with which the script has been called
-
the number of parameters which have been set within the script by
set -- foo bar -
(when used within a function) the number of parameters with which a function has been called (
setwould work there, too).
This is explained in the bash man page in the block “Special Parameters”.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0