BASH之前从未见过这个用法:
pidfile=${PIDFILE-/var/run/service.pid}
我以前从未见过/使用过的部分是${PIDFILE-部分。
如果定义了$PIDFILE则表示使用$PIDFILE如果$PIDFILE未定义,则表示使用/var/run/service.pid 。
从一个新的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 man页面的旧时代开始的。
${parameter-word} If parameter is set then substitute its value; otherwise substitute word.
你可能已经看到的另一种forms是${parameter:-word} 。 它是相似的,但行为不同,如果parameter设置为空string。
${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}如何扩展为空string,因为NULLVAR 已定义。
要获得完整的解释,请运行“man bash”并input“/ Parameter Expansion”来search参数扩展。
在这个解释中$ {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.
感谢Dennis对于set与null的修正。
米克尔:
不应该像pidfile=${PIDFILE:-/var/run/service.pid}那样解释吗?