大网数据广告活动
服务器运维问答

What does a minus sign inside of dollar brackets of a shell script mean?

· 52CE 我爱测

In an existing shell script, I'm seeing some variables referenced that either include or end with a minus sign. For example: PID=${PID-/run/unicorn.pid} and: run_by_init() { ([ "${previous-}" ] && [ "${runlevel-}" ]) || [ "${runl…

问题原文

原帖链接 · Matt Huggins · CC BY-SA 3.0

In an existing shell script, I'm seeing some variables referenced that either include or end with a minus sign. For example:

PID=${PID-/run/unicorn.pid}

and:

run_by_init() {
    ([ "${previous-}" ] && [ "${runlevel-}" ]) || [ "${runlevel-}" = S ]
}

What do the minus signs mean in both of these scenarios?

社区高分解答

原帖链接 · papo · CC BY-SA 4.0

It should be emphasized that this means an unset variable. Not an empty one.
And to put to comparison with :-, which will use default value (the one after minus sign) if variable is unset or null (as in empty string).
Minus without a colon is not seen as often (at least not by me) and has more specific use than :- It's not even mentioned on GNU manual and not in my man bash, but it's described for example on tldp.

In cases where you need to substitute default value, when the variable doesn't hold sensible value. The later is more suitable.

PID=${PID-/run/unicorn.pid}
PID might have been used and later emptied using PID="" in the script. This association will than fail and PID will stay an empty string ""

PID=${PID:-/run/unicorn.pid}
PID will become "/run/unicorn.pid" if it was unset, but even if it was null ("") before.

A construct without a default value ${previous-} is debated to be a safe-guard against someone having set -u

set -u|nounset

Treat unset variables and parameters other than the special parameters ‘@’ or ‘*’ as an error when performing parameter expansion. An error message will be written to the standard error, and a non-interactive shell will exit.
https://www.gnu.org/software/bash/manual/html_node/The-Set-Builtin.html

set -u
[ "${previous}" ] || echo "This will fail"
[ "${previous-}" ] || echo "This works"

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2015-04-01)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0 / CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。