Hello World

shell [ ] 和 [[ ]] 区别

【参考文章】:shell if [[ ]]和[ ]区别 || &&

【参考文章】:Shell test 命令

1. [ ] 和 test

  test  等同于 [ ] 

  可用于判断某个条件是否为真。可用于 字符串,数值和文件的测试。

1.1 字符串

  可使用的参数如下:

  也可以使用 ==(等价于=)

   示例:


read -p "str1:" str1
read -p "str2:" str2
# [ 后面和 ] 前面必须使用空格隔开
# = 两端必须使用空格隔开
if [ "$str1" = "$str2" ]
then
    echo "str1 == str2"
else
    echo "str1 != str2"
fi

1.2 数值

   示例:

 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

3. 文件

  示例:

 read -p "输入文件路径:" filepath

 if [ -e $filepath ]
 then
     echo "文件存在"
 else
    echo "文件不存在"
 fi

2. [[ ]]

  [[ ]] 比 [ ] 更强大

  使用 =~ 操作符时, 支持 shell 的正则表达式

 read -p "str1:" str1

 str2=a{3}

# [ 后面和 ] 前面必须使用空格隔开
# = 两端必须使用空格隔开
if [[ ${str1} =~ ${str2} ]]
then
    echo "str1 == str2"
else
    echo "str1 != str2"
fi

 

posted @ 2019-10-11 19:02  小小忧愁米粒大  阅读(1459)  评论(0编辑  收藏  举报
瞅啥瞅,好好看书