dev*_*ium 564 bash function parameter-passing
假设我已经定义了一个function abc()将处理与分析传递给我的脚本的参数相关的逻辑.
如何将我的bash脚本收到的所有参数传递给它?params的数量是可变的,所以我不能像这样硬编码传递的参数:
abc $1 $2 $3 $4
Run Code Online (Sandbox Code Playgroud)
编辑.更好的是,我的函数有没有办法访问脚本参数的变量?
Gor*_*son 904
宠儿:在使用时$@,你应该(几乎)总是把它放在双引号中,以避免错误地使用空格中的参数:
abc "$@"
Run Code Online (Sandbox Code Playgroud)
haj*_*mie 139
我需要对此进行修改,我希望这对其他人有用:
function diffs() {
diff "${@:3}" <(sort "$1") <(sort "$2")
}
Run Code Online (Sandbox Code Playgroud)
该"${@:3}"部分表示从3开始的数组的所有成员.因此,此函数通过将前两个参数传递给diff通过sort然后将所有其他参数传递给diff来实现排序的diff,因此您可以类似于diff调用它:
diffs file1 file2 [other diff args, e.g. -y]
Run Code Online (Sandbox Code Playgroud)
Mia*_*rke 52
使用$@变量,该变量扩展为由空格分隔的所有命令行参数.
abc "$@"
Run Code Online (Sandbox Code Playgroud)
Giu*_*one 44
这是一个简单的脚本:
#!/bin/bash
args=("$@")
echo Number of arguments: $#
echo 1st argument: ${args[0]}
echo 2nd argument: ${args[1]}
Run Code Online (Sandbox Code Playgroud)
$#是脚本收到的参数数量.我发现使用数组更容易访问它们:该args=("$@")行将所有参数放在args数组中.要访问它们使用${args[index]}.
rob*_*uck 34
值得一提的是,您可以使用此语法指定参数范围.
function example() {
echo "line1 ${@:1:1}"; #First argument
echo "line2 ${@:2:1}"; #Second argument
echo "line3 ${@:3}"; #Third argument onwards
}
Run Code Online (Sandbox Code Playgroud)
我没有看到它提到过.
Viv*_*sse 18
abc "$@"
Run Code Online (Sandbox Code Playgroud)
$@ 表示为bash脚本提供的所有参数.
and*_*ien 14
abc“ $ @”通常是正确的答案。但是我试图将参数传递给su命令,并且没有任何引号可以阻止错误su: unrecognized option '--myoption'。实际上对我有用的是将所有参数作为单个字符串传递:
abc "$*"
Run Code Online (Sandbox Code Playgroud)
我的确切情况(我确定有人需要这个)在我的.bashrc中
# run all aws commands as Jenkins user
aws ()
{
sudo su jenkins -c "aws $*"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
277315 次 |
| 最近记录: |