How to pass all arguments passed to my bash script

2019-01-12 13:06发布

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?

7条回答
放我归山
2楼-- · 2019-01-12 13:46
abc "$@"

$@ represents all the parameters given to your bash script.

查看更多
Rolldiameter
3楼-- · 2019-01-12 13:47

Pet peeve: when using $@, you should (almost) always put it in double-quotes to avoid misparsing of argument with spaces in them:

abc "$@"
查看更多
叛逆
4楼-- · 2019-01-12 13:51

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]}.

查看更多
Root(大扎)
5楼-- · 2019-01-12 13:52

Use the $@ variable, which expands to all command-line parameters separated by spaces.

abc "$@"
查看更多
叼着烟拽天下
6楼-- · 2019-01-12 13:54

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 $*"
}
查看更多
啃猪蹄的小仙女
7楼-- · 2019-01-12 14:05

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.

查看更多
登录 后发表回答