【参考文章】:shell if [[ ]]和[ ]区别 || &&
【参考文章】:Shell test 命令
test 等同于 [ ]
可用于判断某个条件是否为真。可用于 字符串,数值和文件的测试。
可使用的参数如下:
也可以使用 ==(等价于=)
示例:
read -p "str1:" str1 read -p "str2:" str2 # [ 后面和 ] 前面必须使用空格隔开 # = 两端必须使用空格隔开 if [ "$str1" = "$str2" ] then echo "str1 == str2" else echo "str1 != str2" fi
示例:
read -p "num1:" num1 read -p "num2:" num2 # [ 后面和 ] 前面必须使用空格隔开 # = 两端必须使用空格隔开 if [ "$num1" -eq "$num2" ] then echo "num1 == num2" else echo "num1 != num2" fi if [ "$num1" -gt "$num2" ] then echo "num1 > num2" else echo "num1 <= num2" fi
示例:
read -p "输入文件路径:" filepath if [ -e $filepath ] then echo "文件存在" else echo "文件不存在" fi
[[ ]] 比 [ ] 更强大
字符串比较时,如果右边没有使用双引号,则将右边的字符串作为一个模式;如果右边的字符串使用的双引号,则将其作为一个文本字符串。
使用 =~ 操作符时, 支持 shell 的正则表达式
逻辑组合时可以使用 && || 或者 test 的 -a -o
原文:https://www.cnblogs.com/virgosnail/p/11656187.html