本文翻译自:How to pass all arguments passed to my bash script to a function of mine? [duplicate]
Let's say I have defined a function abc()
that will handle the logic related to analyzing the arguments passed to my script. 假设我已经定义了一个function abc()
,它将处理与分析传递给脚本的参数有关的逻辑。
How can I pass all arguments my bash script has received to it? 如何将bash脚本收到的所有参数传递给它? 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? 更好的是,我的函数是否可以访问脚本参数的变量?
#1楼
参考:https://stackoom.com/question/FzVJ/如何将传递给我的bash脚本的所有参数传递给我的函数-重复
#2楼
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: "${@:3}"
部分表示从3开始的数组的所有成员。因此,此函数通过将前两个参数传递给diff并随后将所有其他参数传递给diff来实现排序的diff,因此您可以类似于diff来称呼它:
diffs file1 file2 [other diff args, e.g. -y]
#3楼
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. 我没有看到它提到。
#4楼
abc "$@"
$@
表示提供给bash脚本的所有参数。
#5楼
使用$@
变量,该变量将扩展为所有用空格分隔的命令行参数。
abc "$@"
#6楼
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. 我发现使用数组更容易访问它们: args=("$@")
行将所有参数放入args
数组中。 To access them use ${args[index]}
. 要访问它们,请使用${args[index]}
。