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

例如,我的脚本名为foo.sh,调用bar.sh。

foo.sh:

bar $1 $2 $3 $4

如何在不显式指定每个参数的情况下做到这一点?


当前回答

bash和其他类似bourne的炮弹:

bar "$@"

其他回答

"${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'"

如果在带引号的字符串中包含$@和其他字符,当有多个参数时,行为是非常奇怪的,只有第一个参数包含在引号中。

例子:

#!/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'

我的SUN Unix有很多限制,甚至“$@”也没有按预期解释。我的变通方法是${@}。例如,

#!/bin/ksh
find ./ -type f | xargs grep "${@}"

顺便说一下,我必须有这个特定的脚本,因为我的Unix也不支持grep -r

使用“$@”(适用于所有POSIX兼容程序)。

[…), bash提供了“$@”变量,它扩展为所有用空格分隔的命令行参数。

以Bash为例。

#!/usr/bin/env bash
while [ "$1" != "" ]; do
  echo "Received: ${1}" && shift;
done;

只是认为在尝试测试args如何进入脚本时,这可能更有用