
以前從未在 BASH 中使用過這個:
pidfile=${PIDFILE-/var/run/service.pid}
我以前從未見過/使用過的部分是該${PIDFILE-
部分。
答案1
這意味著$PIDFILE
如果$PIDFILE
已定義則使用,/var/run/service.pid
如果$PIDFILE
未定義則使用。
從新的 shell 開始:
$ echo ${PIDFILE-/var/run/service.pid}
/var/run/service.pid
現在定義 PIDFILE:
$ PIDFILE=/var/run/myprogram.pid
$ echo ${PIDFILE-/var/run/service.pid}
/var/run/myprogram.pid
這是來自 Bourne Shell 的舊時光sh 手冊頁。
${parameter-word}
If parameter is set then substitute its value;
otherwise substitute word.
您可能已經見過的另一種形式是${parameter:-word}
。它很相似,但如果parameter
設定為空字串,則行為不同。
${parameter:-word}
Use Default Values. If parameter is unset or null,
the expansion of word is substituted. Otherwise,
the value of parameter is substituted.
展示:
$ set | grep NOSUCHVAR # produces no output because NOSUCHVAR is not defined
$ echo ${NOSUCHVAR-default}
default
$ echo ${NOSUCHVAR:-default}
default
$ NULLVAR=
$ set | grep NULLVAR # produces output because NULLVAR is defined
NULLVAR=
$ echo ${NULLVAR-default}
$ echo ${NULLVAR:-default}
default
請注意如何${NULLVAR-default}
擴展到空字串,因為NULLVAR
是定義的。
要獲得完整的解釋,請運行“man bash”並蒐索參數擴充透過輸入“/參數擴展”。
${parameter-word} 位元在此解釋中被隱藏:
When not performing substring expansion, using the forms documented below,
bash tests for a parameter that is unset or null. Omitting the colon results
in a test only for a parameter that is unset.
感謝丹尼斯對 set 與 null 的更正。
答案2
米克爾:
不應該是
pidfile=${PIDFILE:-/var/run/service.pid}
你解釋的方式嗎?