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

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

foo.sh:

bar $1 $2 $3 $4

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


当前回答

我知道这个问题已经得到了很好的回答,但这里有一个“$@”$@“$*”和$*之间的比较

测试脚本内容:

# cat ./test.sh
#!/usr/bin/env bash
echo "================================="

echo "Quoted DOLLAR-AT"
for ARG in "$@"; do
    echo $ARG
done

echo "================================="

echo "NOT Quoted DOLLAR-AT"
for ARG in $@; do
    echo $ARG
done

echo "================================="

echo "Quoted DOLLAR-STAR"
for ARG in "$*"; do
    echo $ARG
done

echo "================================="

echo "NOT Quoted DOLLAR-STAR"
for ARG in $*; do
    echo $ARG
done

echo "================================="

现在,运行带有各种参数的测试脚本:

# ./test.sh  "arg with space one" "arg2" arg3
=================================
Quoted DOLLAR-AT
arg with space one
arg2
arg3
=================================
NOT Quoted DOLLAR-AT
arg
with
space
one
arg2
arg3
=================================
Quoted DOLLAR-STAR
arg with space one arg2 arg3
=================================
NOT Quoted DOLLAR-STAR
arg
with
space
one
arg2
arg3
=================================

其他回答

如果你确实希望传递相同的参数,请使用“$@”而不是普通的$@。

观察:

$ 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为例。

工作正常,除非您有空格或转义字符。我没有找到在这种情况下捕获参数并发送到脚本中的ssh的方法。

这可能是有用的,但如此丑陋

_command_opts=$( echo "$@" | awk -F\- 'BEGIN { OFS=" -" } { for (i=2;i<=NF;i++) { gsub(/^[a-z] /,"&@",$i) ; gsub(/ $/,"",$i );gsub (/$/,"@",$i) }; print $0 }' | tr '@' \' )

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