在bash shell脚本中传播所有参数
我正在写一个非常简单的脚本来调用另一个脚本,我需要将参数从当前脚本传播到正在执行的脚本。
例如,我的脚本名称是foo.sh
并调用bar.sh
foo.sh:
bar $1 $2 $3 $4
我怎样才能做到这一点,没有明确指定每个参数?
如果你真的希望你的parameter passing相同,使用"$@"
而不是简单的$@
。
注意:
$ 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提供了“$ @”variables,该variables扩展为以空格分隔的所有命令行参数。
从Bash的例子 。
#!/usr/bin/env bash while [ "$1" != "" ]; do echo "Received: ${1}" && shift; done;
只是觉得这可能是一个更有用的时候,试图testing如何参数进入你的脚本
我的SUN Unix有很多限制,甚至“$ @”也没有被解释为需要。 我的解决方法是$ {@}。 例如,
#!/bin/ksh find ./ -type f | xargs grep "${@}"
顺便说一句,我必须有这个特定的脚本,因为我的Unix也不支持grep -r
我意识到这已经得到了很好的回答,但是这里比较了“$ @”$ @“$ *”和$ *
testing脚本的内容:
# 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 "================================="
现在,用各种参数运行testing脚本:
# ./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 =================================
工作正常,除非你有空格或转义字符。 我没有find在这种情况下捕获参数的方法,并发送到脚本内的ssh。
这可能是有用的,但是非常难看
_command_opts=$( echo "$@" | awk -F\- 'BEGIN { OFS=" -" } { for (i=2;i<=NF;i++) { gsub(/^[az] /,"&@",$i) ; gsub(/ $/,"",$i );gsub (/$/,"@",$i) }; print $0 }' | tr '@' \' )