【发布时间】:2026-01-07 03:25:02
【问题描述】:
如何以简洁、惯用的方式为 bash 变量设置默认值?这看起来很丑:
if [[ ! -z "$1" ]]; then
option="$1"
else
option="default"
fi
【问题讨论】:
如何以简洁、惯用的方式为 bash 变量设置默认值?这看起来很丑:
if [[ ! -z "$1" ]]; then
option="$1"
else
option="default"
fi
【问题讨论】:
你可以使用:
option=${1:-default}
如果给出了第一个命令行参数并且不为空,则这会将选项设置为第一个命令行参数。否则,它将选项设置为默认值。参看Bash reference manual了解参数扩展的详细信息和这种形式的一些有用的变体。
【讨论】:
${1-default},那么它将区分未设置和已设置但为空的参数。
default value : ${parameter:-word} \
assign default value : ${parameter:=word} |_ / if unset or null -
error if empty/unset : ${parameter:?mesg} | \ use no ":" for unset only
use word unless empty/unset : ${parameter:+word} /
【讨论】:
对于使用other而不是分配一个默认值,Toxaris 已经介绍过,值得一提的是-z 有一个反向测试,所以不是
if [[ ! -z "$1" ]]; then
do_something
fi
你可以简单地写:
if [ -n "$1" ]; then
do_something
fi
如果没有else 分支,可以将其缩短为:
[ -n "$1" ] && do_something
【讨论】:
if [ "$1" ]; then ...
[ -n "$1" ] && do_something 有一个缺点 - 如果设置了 set -e...
set -e 而言,[...] && command 与if [...]; then command; fi 相同。 [...] 命令可以安全地失败,command 在运行失败时将退出 shell。