我正在编写一个调用另一个脚本的非常简单的脚本,我需要将参数从当前脚本传播到我正在执行的脚本。
例如,我的脚本名为foo.sh,调用bar.sh。
foo.sh:
bar $1 $2 $3 $4
如何在不显式指定每个参数的情况下做到这一点?
我正在编写一个调用另一个脚本的非常简单的脚本,我需要将参数从当前脚本传播到我正在执行的脚本。
例如,我的脚本名为foo.sh,调用bar.sh。
foo.sh:
bar $1 $2 $3 $4
如何在不显式指定每个参数的情况下做到这一点?
当前回答
使用“$@”(适用于所有POSIX兼容程序)。
[…), bash提供了“$@”变量,它扩展为所有用空格分隔的命令行参数。
以Bash为例。
其他回答
#!/usr/bin/env bash
while [ "$1" != "" ]; do
echo "Received: ${1}" && shift;
done;
只是认为在尝试测试args如何进入脚本时,这可能更有用
如果你确实希望传递相同的参数,请使用“$@”而不是普通的$@。
观察:
$ 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:
使用“$@”(适用于所有POSIX兼容程序)。
[…), bash提供了“$@”变量,它扩展为所有用空格分隔的命令行参数。
以Bash为例。
如果在带引号的字符串中包含$@和其他字符,当有多个参数时,行为是非常奇怪的,只有第一个参数包含在引号中。
例子:
#!/bin/bash
set -x
bash -c "true foo $@"
收益率:
$ bash test.sh bar baz
+ bash -c 'true foo bar' baz
但是先赋值给另一个变量:
#!/bin/bash
set -x
args="$@"
bash -c "true foo $args"
收益率:
$ bash test.sh bar baz
+ args='bar baz'
+ bash -c 'true foo bar baz'
Bar "$@"将等价于Bar "$1" "$2" "$3" "$4"
注意,引号很重要!
"$@", $@, "$*"或$*将在此stackoverflow回答中描述的转义和连接方面各自表现略有不同。
一个密切相关的用例是在一个参数中传递所有给定的参数,就像这样:
Bash -c“bar \”$1\“$2\”$3\“$4\””。
我使用@kvantour的答案的一个变体来实现这一点:
Bash -c "bar $(printf - ' ' %s ' ' ' $@")"