如何讓函數傳遞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)。 –