温馨提示×

shell判断字符串不为空的方法是什么

小亿
243
2024-01-30 10:15:54
栏目: 编程语言

在shell中,可以使用以下几种方法判断字符串是否为空:

  1. 使用-n选项判断字符串长度是否为非零:
if [ -n "$string" ]; then
    echo "String is not empty"
else
    echo "String is empty"
fi
  1. 使用-z选项判断字符串长度是否为零:
if [ -z "$string" ]; then
    echo "String is empty"
else
    echo "String is not empty"
fi
  1. 使用双括号[[]]进行比较:
if [[ -n $string ]]; then
    echo "String is not empty"
else
    echo "String is empty"
fi

请注意,在shell脚本中,变量的引用一般需要使用双引号,以避免特殊字符的解释和空字符串的问题。

0