为什么需要"$ {1: - }"?

Lei*_*Mou 1 bash

阅读这个简单的bash函数后,我有点困惑:

log_daemon_msg() {
    if [ -z ${1:-} ]; then
        return 1
    fi
    echo $@
}
Run Code Online (Sandbox Code Playgroud)

根据man 1 bash,说:

$ {参数:-word}

   Use Default Values. If parameter is unset or null, the expansion of word is
   substituted. Otherwise, the value of parameter is substituted.
Run Code Online (Sandbox Code Playgroud)

如果$1为NULL或未设置,则值为$1NULL.这就是我的困惑来自:为什么有必要为$ 1分配NULL值,即使事实$1为NULL或未设置已知?如果我的理解是错误的,请纠正我.谢谢!

Rom*_*aka 8

一个可能的原因是兼容-u一个有用的shell标志,每当变量/参数未绑定时就会发出错误信号.

$ set -u
$ echo ${1:-}

$ echo $1
bash: $1: unbound variable
Run Code Online (Sandbox Code Playgroud)