2017-09-01 20 views

回答

1

一種方法是使用bash array slice notation

foo() { 
    echo "[$1]" 
    echo "[$2]" 
    echo "[${@:3}]" 
} 

產地:

$ foo a b c d ef 
[a] 
[b] 
[c d ef] 

,你會在你的代碼實現爲:

if [ "$2" == "exec" ]; then 
    other_script execute "${@:3}" 
fi 

如果你需要說的第3和第第四個參數,您可以將長度應用於切片:

other_script execute "${@:3:2}" # :2 is a length specification 

另一種方式,如果你並不需要爭論$1$2不再是僅僅將它們轉移出來的樣子:

foo=${1:?Missing argument one} 
bar=${2:-Default} 
shift 2 

echo "[email protected]" # the first two args are gone, so this is now args #3 on 

我更喜歡這種方式,說實話,一對夫婦的原因:

  1. 編號參數很難記住:命名參數更清晰。
  2. 陣列切片符號不是衆所周知的(根據我的經驗),所以它可能會導致一些混淆與未來的維護。
+1

我真的很喜歡這個偉大的答案的細節! – Martlark