歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> shell編程中的條件判斷

shell編程中的條件判斷

日期:2017/3/1 9:09:19   编辑:SHELL編程

shell編程中的條件判斷
條件
if-then
case

if-then
單條件
if command
then
commands
fi
當command返回碼為0時 條件成立

if.sh

#! /bin/bash

if date
then
        echo "command exec"
fi

if date123
then
        echo "command exec1"
fi

echo "out if"

[root@localhost110 sh]# ./if.sh
2016年 10月 29日 星期六 10:39:18 EDT
command exec
./if.sh: line 8: date123: command not found
out if

全覆蓋

if command
then
  commands
else
  commands
fi

if.sh

#! /bin/bash
if date1
then
        echo "command"
        echo "ok"
else
        echo "commond1"
        echo "fail"
fi

[root@localhost110 sh]# ./if.sh
./if.sh: line 2: date1: command not found
commond1
fail

條件嵌套

if command1
then
  commands
  if command2
  then
    commands
  fi
  commands
fi

多條件
if command1
then
  commands
elif command2
then
  commands
else
  commands
fi

test命令:
第一種形式
if test condition
then
  commands
fi
第二種形式
中括號 []
if [ condition ]
then
commands
fi

復合條件判斷
[ condition1 ] && [ condition2 ]
[ condition1 ] || [ condition2 ]

condition左右2邊一定需要有空格 否者不能正確的執行

三類條件
  數值比較
  字符串比較
  文件比較
if.sh

echo plese input a num

read num

if [ $num -gt 10 ]
then
        echo "the num>10"
fi

if [ $num -lt 10 ]  && [ $num -gt 5 ]
then
        echo "the 5<num<10"
fi

[root@localhost110 sh]# ./if.sh plese input a num 11 the num>10

常用判斷條件
數值比較
=      n1 -eq n2
>=    n1 -ge n2
>    n1 -gt n2
<    n1 -lt n2
<=    n1 -le n2
!= n1 -ne n2
compare.sh及其調用結果

#! /bin/bash

if [ $1 -eq $2 ]
then
        echo "$1=$2"
elif [ $1 -gt $2 ]
then
        echo "$1>$2"
else
        echo "$1<$2"
fi
運行結果
[root@localhost110 sh]# ./compare.sh  1 1
1=1
[root@localhost110 sh]# ./compare.sh  1 2
1<2
[root@localhost110 sh]# ./compare.sh  2 1
2>1
[root@localhost110 sh]# ./compare.sh   1 a
./compare.sh: line 3: [: a: integer expression expected
./compare.sh: line 6: [: a: integer expression expected
1<a

字符串比較
str1 = str2 相同
str1 != str2 不同
str1 > str2 str1比str2大 (ascll碼逐位比較)
str1 < str2 str1比str2小
-n str1 字符串長度是否非0
-z str1 字符串長度是否為0

文件比較
-d file 檢查file是否存在並是一個目錄
-e file 檢查file是否存在
-f file 檢查file是否存在並是一個文件
-s file 檢查file是否存在並非空

file1 -nt file2 檢查file1是否比file2新
file1 -ot file2 檢查file1是否比file2舊

-r file 檢查file是否存在並可讀
-w file 是否存在並可寫
-x file 是否存在並可執行
-O file 是否存在並屬當前用戶所有
-G file 是否存在並且默認組與當前用戶相同

高級判斷
(( expression )) 高級數學表達式
[[ expression ]] 高級字符串比較

if (($1<$2))
then
echo $1,$2;
echo $1\<$2;
elif (($1==$2))
then echo $1==$2
else
echo $1\>$2
fi 

case

case variable in
pattern1 | pattern2) commands1;;
pattern3) commands3;;
*) default commands ;;
esac

#! /bin/bash
case $1 in 1|11|111)
echo 1_$1;; 2)
echo 2_$1;
echo 2_$1;;
3)
echo 3_$1;;
esac

Copyright © Linux教程網 All Rights Reserved