协慌网

登录 贡献 社区

在 bash shell 脚本中传播所有参数

我正在编写一个非常简单的脚本,该脚本调用另一个脚本,并且需要将参数从当前脚本传播到正在执行的脚本。

例如,我的脚本名称是foo.sh并调用bar.sh

foo.sh:

bar $1 $2 $3 $4

如何在不显式指定每个参数的情况下执行此操作?

答案

如果您实际上希望以相同的方式传递参数,请使用"$@"而不是普通的$@

观察:

$ cat foo.sh
#!/bin/bash
baz.sh $@

$ cat bar.sh
#!/bin/bash
baz.sh "$@"

$ cat baz.sh
#!/bin/bash
echo Received: $1
echo Received: $2
echo Received: $3
echo Received: $4

$ ./foo.sh first second
Received: first
Received: second
Received:
Received:

$ ./foo.sh "one quoted arg"
Received: one
Received: quoted
Received: arg
Received:

$ ./bar.sh first second
Received: first
Received: second
Received:
Received:

$ ./bar.sh "one quoted arg"
Received: one quoted arg
Received:
Received:
Received:

对于bash和其他类似 Bourne 的外壳:

java com.myserver.Program "$@"

使用"$@" (适用于所有POSIX兼容版本)。

bash 具有 “$ @” 变量,该变量扩展为所有用空格分隔的命令行参数。

Bash 为例