bash - bash中未设置和空变量之间的区别

标签 bash

使用 bash,检查变量是否为空的最佳方法是什么?

如果我使用:

if [ -z "$VAR" ]

正如论坛中所建议的那样,这适用于未设置的变量,但当变量已设置但为空时它是正确的。 有什么建议吗?

最佳答案

如果变量未设置,

${var+set} 不替换任何内容,如果变量设置为包括空字符串在内的任何内容,则 set 不替换任何内容。仅当变量设置为非空字符串时,${var:+set} 才替换 set。您可以使用它来测试任何一种情况:

if [ "${foo+set}" = set ]; then
    # set, but may be empty
fi

if [ "${foo:+set}" = set ]; then
    # set and nonempty
fi

if [ "${foo-unset}" = unset ]; then
    # foo not set or foo contains the actual string 'unset'
    # to avoid a potential false condition in the latter case,
    # use [ "${foo+set}" != set ] instead
fi

if [ "${foo:-unset}" = unset ]; then
    # foo not set or foo empty or foo contains the actual string 'unset'
fi

关于bash - bash中未设置和空变量之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5406858/

相关文章:

ios - 内部版本号Xcode递增(在最后一个组件上)

php - PHP 中的 cURL : curl_exec() or exec ('curl' )?

linux - 如何在 bash 脚本中传递两个参数或参数

bash - 在批处理文件中将反斜杠转换为转发

bash - unix 排序,带主键和辅助键

linux - 对文件夹中的所有文件运行命令的 Bash 脚本失败

linux - 如何使用 echo 编写非 ASCII 字符?

linux - 使用 sed 替换与导出变量匹配的模式

linux - 使用 set -x 时重定向 bash 脚本中的所有输出,捕获 pid 和所有输出

bash - 自定义 Bash 提示符正在覆盖自身