20.5 Logic judgment in shell script 20.6 File directory attribute judgment 20.7 if special usage 20.8/20.9 case judgment

20.5 Logical judgment in shell scripts

格式1:if 条件 ; then 语句; fi
格式2:if 条件; then 语句; else 语句; fi
格式3:if …; then … ;elif …; then …; else …; fi
逻辑判断表达式:if [ $a -gt $b ]; if [ $a -lt 5 ]; if [ $b -eq 10 ]等  , 注意到处都是空格
-gt (>); -lt(<); -ge(>=); -le(<=);-eq(==); -ne(!=)  
可以使用 && || 结合多个条件
if [ $a -gt 5 ] && [ $a -lt 10 ]; then
if [ $b -gt 5 ] || [ $b -lt 3 ]; then

用 (( )) 括起来  就可以使用判断符号了 如  if (( $a>1 ))

-a 与
-o 或
! 非

20.6 Judgment of file directory attributes

[ -f file ]判断是否是普通文件,且存在    /  [ ! -f file ]判断是否不是普通文件,且不存在
[ -d file ] 判断是否是目录,且存在
[ -e file ] 判断文件或目录是否存在
[ -r file ] 判断文件是否可读
[ -w file ] 判断文件是否可写
[ -x file ] 判断文件是否可执行

If  [ $a == $b ]                 如果string1等于string2 字符串允许使用赋值号做等号
if  [ $string1 !=  $string2 ]   如果string1不等于string2       
if  [ -n $string  ]             如果string 非空(非0),返回0(true)  
if  [ -z $string  ]             如果string 为空
if  [ $sting ]                  如果string 非空,返回0 (和-n类似)    

20.7 Special uses of if

if [ -z "$a" ]  这个表示当变量a的值为空时会怎么样
if [ -n "$a" ] 表示当变量a的值不为空
if grep -q '123' 1.txt; then  表示如果1.txt中含有'123'的行时会怎么样
if [ ! -e file ]; then 表示文件不存在时会怎么样
if (($a<1)); then …等同于 if [ $a -lt 1 ]; then…
[ ] 中不能使用<,>,==,!=,>=,<=这样的符号

20.8/20.9 case judgment

格式 case  变量名 in 
                     value1)
                          command
                          ;;
                     value2)
                          command
                          ;;
                      *)
                        commond
                            ;;
                      esac

在case程序中,可以在条件中使用|,表示或的意思, 比如    
2|3) 
    command
    ;;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325521133&siteId=291194637