如何让函数传递3个参数而不是4个?在脚本中引用参数不会帮助我。例如身体test.sh的脚本:用函数引用BASH参数
func1(){
echo "Func1: Amount arguments: $#, Passed arguments: [email protected]";
for i in [email protected]; do
echo "ARG=$i";
done;
}
echo "Body: Amount arguments: $#, Passed arguments: [email protected]";
func1 [email protected];
# quoting with single or double quote
res="";
for i in "${@}"; do
# try to figure out if quoting was required for the $i:
grep -q "[[:space:]]" <<< "$i" && res="${res} \"${i}\"" || res="${res} ${i}";
done;
echo "Quoted arguments: $res";
func1 $res;
我旁边的参数执行脚本:
bash ./test.sh 1 2 "3 4"
结果:
Body: Amount arguments: 3, Passed arguments: 1 2 3 4
Func1: Amount arguments: 4, Passed arguments: 1 2 3 4
ARG=1
ARG=2
ARG=3
ARG=4
Quoted arguments: 1 2 "3 4"
Func1: Amount arguments: 4, Passed arguments: 1 2 "3 4"
ARG=1
ARG=2
ARG="3
ARG=4"
我想要得到的第三个参数为 “3 4” 。怎么做?谢谢。
嗯......它真的有用,如果引用 - “$ @”。这对我来说是最好的解决方案,不需要额外的代码。这很奇怪,但之前我试图做到这一点,但我没有成功,但现在我检查了一切正常。谢谢! – dva
尽管其他解决方案对嵌套函数更通用,但对于您的代码而言,这应该足够了。还要注意'for'循环中的引号(这些是你以前可能忘记的那些)。 –
如果有用,请考虑[接受答案](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 –