2012-12-13 67 views
5

在我的腳本「script.sh」中,我想將第一個和第二個參數存儲到某個變量中,然後將其餘變量存儲到另一個單獨的變量中。我必須使用什麼命令來執行此任務? 請注意,傳遞給腳本的參數數量會有所不同。將傳遞的參數存儲在單獨的變量中-shell腳本

當我運行在控制檯

./script.sh abc def ghi jkl mn o p qrs xxx #It can have any number of arguments 

在這種情況下的命令,我想我的腳本保存「ABC」和「DEF」的一個變量。 「ghi jkl mn o p qrs xxx」應該存儲在另一個變量中。

回答

8

如果你只是想連接的參數:

#!/bin/sh 

first_two="$1 $2" # Store the first two arguments 
shift    # Discard the first argument 
shift    # Discard the 2nd argument 
remainder="$*"  # Store the remaining arguments 

請注意,這會破壞原來的位置參數,並且不能可靠地重建。如果需要更多的工作:

#!/bin/sh 

first_two="$1 $2" # Store the first two arguments 
a="$1"; b="$2"  # Store the first two argument separately 
shift    # Discard the first argument 
shift    # Discard the 2nd argument 
remainder="$*"  # Store the remaining arguments 
set "$a" "$b" "[email protected]" # Restore the positional arguments 
4

切片[email protected]陣列。

var1=("${@:1:2}") 
var2=("${@:3}") 
+0

注意,因爲這些存儲陣列(這是做正確的方式),就必須用一種特殊的語法擴展:'回聲「第一two =「」$ {var1 [@]}「; echo「remaining =」「$ {var2 [@]}」' –

相關問題