$ 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:
17
我意识到这已经得到了很好的解答,但这里是“$ @”$ @“$ *”和$ *之间的比较
测试脚本的内容:
# 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
=================================
8 回答
使用
"$@"
(适用于所有POSIX兼容机) .从Bash by example起 .
我的SUN Unix有很多限制,甚至“$ @”也没有被解释为所希望的 . 我的解决方法是$ {@} . 例如,
顺便说一句,我必须有这个特殊的脚本,因为我的Unix也不支持grep -r
对于bash和其他类似Bourne的shell:
工作正常,除非您有空格或转义字符 . 在这种情况下我找不到捕获参数的方法并发送到脚本内的ssh .
这可能很有用但很难看
如果您真的希望您的参数传递相同,请使用
"$@"
而不是plain$@
.注意:
我意识到这已经得到了很好的解答,但这里是“$ @”$ @“$ *”和$ *之间的比较
测试脚本的内容:
现在,使用各种参数运行测试脚本:
如果在带有其他字符的带引号的字符串中包含
$@
,则当存在多个参数时,行为非常奇怪,只有第一个参数包含在引号内 .例:
产量:
但首先分配给另一个变量:
产量:
只是认为在尝试测试args如何进入脚本时可能会更有用