Bash if 判断空字符串笔记 Linux 2024-04-02 阅读时长: 1 分钟 阅读辅助 专注模式 段落导读 英文词首加粗 老生常谈的if判断字符串加x的问题 代码 1 2 3 4 5 6 7 8 9 10 if [ "$3"x = "r"x ] string='My string'; if [ $string = "My" ]; then echo "It's there!"; else echo "xxxx"; fi 主要是双括号与单括号的情况区分 双括号的情况下是不需要用x来替代的 单括号的情况下,不加x,变量为空时,会报错 执行报错结果 代码 1 2 3 4 5 6 7 8 9 10 11 12 13 [root@iZf8z68utftnb7w6jdl1f0Z ~]# cat test.sh string=''; if [ $string = "My" ]; then echo "It's there!"; else echo "xxxx"; fi [root@iZf8z68utftnb7w6jdl1f0Z ~]# bash test.sh test.sh: line 4: [: =: unary operator expected xxxx [root@iZf8z6