2012-12-07 58 views
17

如何爲Bash中的位置參數賦值?我想爲默認參數分配一個值:分配位置參數

if [ -z "$4" ]; then 
    4=$3 
fi 

指示4不是命令。

回答

29

set內置的設置位置參數

$ set -- this is a test 
$ echo $1 
this 
$ echo $4 
test 

其中--防止東西,看起來像選項(例如-x)的唯一途徑。

你的情況,你可能想:

if [ -z "$4" ]; then 
    set -- "$1" "$2" "$3" "$3" 
fi 

,但它很可能是因爲

if [ -z "$4" ]; then 
    # default the fourth option if it is null 
    fourth="$3" 
    set -- "$1" "$2" "$3" "$fourth" 
fi 

,你可能也想看看參數計算$#而不是測試-z更加清晰。

3

你可以做你想做的與第四參數再次調用腳本:

if [ -z "$4" ]; then 
    $0 "$1" "$2" "$3" "$3" 
    exit $? 
fi 
echo $4 

上面的腳本調用諸如./script.sh one two three將輸出:

+0

'./如果通過PATH訪問腳本,$ 0'將不起作用,'$ 0'本身可以適用於'。/ script'和'/ usr/local/bin/script'等。 – msw