Linux 拨号vps windows公众号手机端

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

lewis 8年前 (2017-01-29) 阅读数 10 #程序编程
文章标签 shell

在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脚本中,变量的引用一般需要使用双引号,以避免特殊字符的解释和空字符串的问题。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门