Let's say I have defined a function abc()
that will handle the logic related to analyzing 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?
This question is related to
bash
function
parameter-passing
Use the $@
variable, which expands to all command-line parameters separated by spaces.
abc "$@"
It's worth mentioning that you can specify argument ranges with this syntax.
function example() {
echo "line1 ${@:1:1}"; #First argument
echo "line2 ${@:2:1}"; #Second argument
echo "line3 ${@:3}"; #Third argument onwards
}
I hadn't seen it mentioned.
abc "$@"
$@
represents all the parameters given to your bash script.
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 :
abc "$*"
My exact case (I'm sure someone else needs this) was in my .bashrc
# run all aws commands as Jenkins user
aws ()
{
sudo su jenkins -c "aws $*"
}
I needed a variation on this, which I expect will be useful to others:
function diffs() {
diff "${@:3}" <(sort "$1") <(sort "$2")
}
The "${@:3}"
part means all the members of the array starting at 3. So this function implements a sorted diff by passing the first two arguments to diff through sort and then passing all other arguments to diff, so you can call it similarly to diff:
diffs file1 file2 [other diff args, e.g. -y]
Here's a simple script:
#!/bin/bash
args=("$@")
echo Number of arguments: $#
echo 1st argument: ${args[0]}
echo 2nd argument: ${args[1]}
$#
is the number of arguments received by the script. I find easier to access them using an array: the args=("$@")
line puts all the arguments in the args
array. To access them use ${args[index]}
.
Source: Stackoverflow.com