Let's say I have defined a function abc()
that will handle all the logic related to analising the arguments passed to my script.
How can I pass all arguments my bash script has received to it? The number of params is variable, so I can't just hardcode the arguments passed like this:
abc $1 $2 $3 $4
Edit. Better yet, is there any way for my function to have access to the script arguments' variables?
$@
represents all the parameters given to your bash script.Pet peeve: when using
$@
, you should (almost) always put it in double-quotes to avoid misparsing of argument with spaces in them:Here's a simple script:
$#
is the number of arguments received by the script. I find easier to access them using an array: theargs=("$@")
line puts all the arguments in theargs
array. To access them use${args[index]}
.Use the
$@
variable, which expands to all command-line parameters separated by spaces.abc "$@" is generally the correct answer. But I was trying to pass a parameter through to an su command, and no amount of quoting could stop the error
su: unrecognized option '--myoption'
. What actually worked for me was passing all the arguments as a single string :My exact case (I'm sure someone else needs this) was in my .bashrc
It's worth mentioning that you can specify argument ranges with this syntax.
I hadn't seen it mentioned.