2017-05-29 40 views
1

如何让函数传递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” 。怎么做?谢谢。

回答

0

您需要在引用的论据函数func1的调用以及函数内部的循环,以便变量扩展不会删除参数中的引号。

#!/bin/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]" 

注意,我已删除了;和每行由于不需要它们的端部。

+0

嗯......它真的有用,如果引用 - “$ @”。这对我来说是最好的解决方案,不需要额外的代码。这很奇怪,但之前我试图做到这一点,但我没有成功,但现在我检查了一切正常。谢谢! – dva

+0

尽管其他解决方案对嵌套函数更通用,但对于您的代码而言,这应该足够了。还要注意'for'循环中的引号(这些是你以前可能忘记的那些)。 –

+0

如果有用,请考虑[接受答案](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)。 –

0

如果要构建需要引用的参数列表,则必须使用数组。句法引号不会嵌套;在展开参数时,内部引号将被视为文字字符。

res=() 
for i in "${@}"; do 
    res+=("$i") 
done 

func "${res[@]}" 

(以上相当于当然,要res=("[email protected]")如果你没有做别的用的i值,除了它添加到阵列。)

+0

谢谢,它的作品 – dva