zoukankan      html  css  js  c++  java
  • shell判断语句

    1.test命令  也可以用[  ]来表示

    返回值为0时为true,返回值为1时为false。

    例1:str1=aaa,str2=bbb

    1)判断字符串是否为空(省略了-n选项,-n选项是不为空,-z选项为空)

    [root@xiaoxiao ~]# str1=aaa
    [root@xiaoxiao ~]# str2=bbb
    [root@xiaoxiao ~]# [ $str1 ]
    [root@xiaoxiao ~]# echo $?
    0
    [root@xiaoxiao ~]# [ -z $str1 ]
    [root@xiaoxiao ~]# echo $?
    1
    [root@xiaoxiao ~]# [ -n $str1 ]
    [root@xiaoxiao ~]# echo $?
    0

    2)判断两个字符串是否相等

    [root@xiaoxiao ~]# [ $str1 = $str2 ]
    [root@xiaoxiao ~]# echo $?
    1

    3)判断两个数字时候相等

    [root@xiaoxiao bin]# str1=3
    [root@xiaoxiao bin]# str2=2
    [root@xiaoxiao bin]# [ $str1 -eq $str2 ] && echo equal || echo noequal
    noequal
    [root@xiaoxiao bin]# str1=2
    [root@xiaoxiao bin]# [ $str1 -eq $str2 ] && echo equal || echo noequal
    equal

    2.逻辑运算符

    # help let

    &与

    |或

    !非

    &&逻辑与 (cmd1 && cmd2,当cmd为ture时执行cmd2,为false时不继续执行cmd2)

    ||逻辑或(cmd1 && cmd2,当cmd1为fasle时执行cmd2,为true时不继续执行cmd2)

    例:str1=aaa;str2=bbb

    [root@xiaoxiao ~]# echo $str1 $str2
    aaa bbb
    [root@xiaoxiao ~]# [ $str1 = $str2 ] && echo truestrs || echo falsestrs
    falsestrs
    [root@xiaoxiao bin]# str1=aaa;str2=aaa
    [root@xiaoxiao bin]# [ $str1 = $str2 ] && echo truestrs || echo falsestrs
    truestrs

    判断str1与str2两个字符串是否相等,cmd1 && cmd2 || cmd3 如果cmd1为真则执行cmd2,如果cmd1 && cmd2 命令cmd1为假则不行cmd2;此时将cmd1 && cmd2 的运算返回值 || cmd3逻辑或时,cmd1 && cmd2 的返回值是false,则执行cmd3。

    ^异或(可以实现两个值得互换,在let运算中)

    [root@xiaoxiao bin]# str1=6;str2=5
    [root@xiaoxiao bin]# str1=$[str1^str2];str2=$[str1^str2];str1=$[str1^str2]
    [root@xiaoxiao bin]# echo $str1 $str2
    5 6

    判断是否是数字 

    [[ "$n" =~ ^[[:digit:]]+$  ]] && echo digit || echo "no digit";[[ "$n" =~ ^[0-9]+$  ]] && echo digit || echo "no digit"

    "[]"中括号中的变量最好用引号,避免造成语法的错误

    判断后缀

    # .表示一个字符 .*表示任意字符 ..*表示至少一个字符

     [[ $filename =~ ..*.sh$ ]] && echo sh ||echo "not sh" 

  • 相关阅读:
    【题解】Killer Names($O(nlog n)$做法)
    【瞎讲】类欧几里得入土教程
    【题解】SDOI2010所驼门王的宝藏(强连通分量+优化建图)
    【题解】ARC101F Robots and Exits(DP转格路+树状数组优化DP)
    【题解】LOJ6060 Set(线性基)
    【题解】CF1056F Write the Contest(三分+贪心+DP)
    【题解】多少个$1$(exBSGS)
    【题解】幼儿园篮球题(范德蒙德卷积+斯特林+NTT)
    【题解】P1373 小a和uim之大逃离
    【题解】地精部落(DP)
  • 原文地址:https://www.cnblogs.com/hekuangquanshuiweiteng/p/12921331.html
Copyright © 2011-2022 走看看