Bash
Bash:為變數分配預設值時出錯
在我的 bash 腳本中:
這有效:
CWD="${1:-${PWD}}"
但是,如果我將其替換為:
CWD="${1:=${PWD}}"
我收到以下錯誤
line #: $1: cannot assign in this way
為什麼我不能分配給 ${1}?
從 bash 的手冊頁:
Positional Parameters A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell's arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameters may not be assigned to with assignment statements. The positional parameters are temporarily replaced when a shell function is executed (see FUNCTIONS below).
之後,在參數擴展下
${parameter:=word} Assign Default Values. If parameter is unset or null, the expansion of word is assigned to parameter. The value of param‐ eter is then substituted. Positional parameters and special parameters may not be assigned to in this way.
如果您想為
$1
問題中的位置參數分配預設值,您可以使用if [ -n "$1" ] then CWD="$1" else shift 1 set -- default "$@" CWD=default fi
在這裡,我使用了
shift
和的組合set
。我剛剛想出了這個,我不確定這是否是更改單個位置參數的正確方法。