我正在编写一个调用另一个脚本的非常简单的脚本,我需要将参数从当前脚本传播到我正在执行的脚本。
例如,我的脚本名为foo.sh,调用bar.sh。
foo.sh:
bar $1 $2 $3 $4
如何在不显式指定每个参数的情况下做到这一点?
我正在编写一个调用另一个脚本的非常简单的脚本,我需要将参数从当前脚本传播到我正在执行的脚本。
例如,我的脚本名为foo.sh,调用bar.sh。
foo.sh:
bar $1 $2 $3 $4
如何在不显式指定每个参数的情况下做到这一点?
当前回答
这里有很多答案推荐带引号或不带引号的$@或$*,但似乎没有人解释这些参数的真正作用以及为什么你应该这样做。所以让我从这个答案中偷取一个很好的总结:
+--------+---------------------------+
| Syntax | Effective result |
+--------+---------------------------+
| $* | $1 $2 $3 ... ${N} |
+--------+---------------------------+
| $@ | $1 $2 $3 ... ${N} |
+--------+---------------------------+
| "$*" | "$1c$2c$3c...c${N}" |
+--------+---------------------------+
| "$@" | "$1" "$2" "$3" ... "${N}" |
+--------+---------------------------+
请注意,引号会造成所有的不同,如果没有引号,两者的行为是相同的。
出于我的目的,我需要将参数从一个脚本传递到另一个脚本,为此最好的选择是:
# file: parent.sh
# we have some params passed to parent.sh
# which we will like to pass on to child.sh as-is
./child.sh $*
注意,在上述情况下,没有引号和$@也可以工作。
其他回答
我的SUN Unix有很多限制,甚至“$@”也没有按预期解释。我的变通方法是${@}。例如,
#!/bin/ksh
find ./ -type f | xargs grep "${@}"
顺便说一下,我必须有这个特定的脚本,因为我的Unix也不支持grep -r
"${array[@]}"是在bash中传递任何数组的正确方式。我想提供一个完整的备忘单:如何准备参数,绕过和处理它们。
Pre.sh -> foo.sh -> bar.sh。
#!/bin/bash
args=("--a=b c" "--e=f g")
args+=("--q=w e" "--a=s \"'d'\"")
./foo.sh "${args[@]}"
#!/bin/bash
./bar.sh "$@"
#!/bin/bash
echo $1
echo $2
echo $3
echo $4
结果:
--a=b c
--e=f g
--q=w e
--a=s "'d'"
bash和其他类似bourne的炮弹:
bar "$@"
如果你确实希望传递相同的参数,请使用“$@”而不是普通的$@。
观察:
$ cat no_quotes.sh
#!/bin/bash
echo_args.sh $@
$ cat quotes.sh
#!/bin/bash
echo_args.sh "$@"
$ cat echo_args.sh
#!/bin/bash
echo Received: $1
echo Received: $2
echo Received: $3
echo Received: $4
$ ./no_quotes.sh first second
Received: first
Received: second
Received:
Received:
$ ./no_quotes.sh "one quoted arg"
Received: one
Received: quoted
Received: arg
Received:
$ ./quotes.sh first second
Received: first
Received: second
Received:
Received:
$ ./quotes.sh "one quoted arg"
Received: one quoted arg
Received:
Received:
Received:
这里有很多答案推荐带引号或不带引号的$@或$*,但似乎没有人解释这些参数的真正作用以及为什么你应该这样做。所以让我从这个答案中偷取一个很好的总结:
+--------+---------------------------+
| Syntax | Effective result |
+--------+---------------------------+
| $* | $1 $2 $3 ... ${N} |
+--------+---------------------------+
| $@ | $1 $2 $3 ... ${N} |
+--------+---------------------------+
| "$*" | "$1c$2c$3c...c${N}" |
+--------+---------------------------+
| "$@" | "$1" "$2" "$3" ... "${N}" |
+--------+---------------------------+
请注意,引号会造成所有的不同,如果没有引号,两者的行为是相同的。
出于我的目的,我需要将参数从一个脚本传递到另一个脚本,为此最好的选择是:
# file: parent.sh
# we have some params passed to parent.sh
# which we will like to pass on to child.sh as-is
./child.sh $*
注意,在上述情况下,没有引号和$@也可以工作。