shell if else 判斷

sh -x 顯示腳本執行過程

[root@localhost ~]# cat 2.sh

#!/bin/bash

echo "hello"

[root@localhost ~]# sh -x 2.sh

+ echo hello

hello


數學運算

[root@localhost ~]# cat 1.sh

#!/bin/bash

a=1

b=2

c=$[$a+$b]

echo $c

[root@localhost ~]# sh 1.sh

3


邏輯判斷if

[root@localhost ~]# cat 3.sh

#!/bin/bash

# 用戶輸入一個數字

read -t 5 -p "Please input a number:" number

# 判斷用戶輸入是否大於5

if [ $number -gt 5 ]

then

# 如果判斷爲真,輸出

echo "number > 5"

fi

# 邏輯判斷符號

# 數學表示  shell表示

#  > -gt

#  < -lt

#  == -eq

#  != -ne

#  >= -ge

#  <= -le


邏輯判斷if...else...

[root@localhost ~]# cat 3.sh

#!/bin/bash

read -t 5 -p "Please input a number:" number

if [ $number -gt 5 ]

then

echo "number > 5"

else

echo "number < 5"

fi


邏輯判斷if...elif...else...

[root@localhost ~]# cat 3.sh

#!/bin/bash

read -t 5 -p "Please input a number:" number

if [ $number -gt 5 ]

then

echo "number > 5"

elif [ $number -lt 5 ]

then

echo "number < 5"

else

echo "number = 5"

fi


if判斷的幾種用法

用法一:判斷/tmp/目錄是否存在,如果存在,屏幕輸出OK,-d是目標類型,也可以是其他類型,如-f,-s等,詳見linux文件類型。第一個是以腳本的形式執行,第二個是以命令行的形式執行

[root@localhost ~]# cat 1.sh

#!/bin/bash

if [ -d /tmp/ ]

then

echo OK;

fi

[root@localhost ~]# bash 1.sh

OK

[root@localhost ~]# if [ -d /tmp/ ]; then echo OK; fi

OK

用法二、判斷目標權限

[root@localhost test]# ll

總用量 4

-rw-r--r-- 1 root root 45 12月  9 19:32 1.sh

[root@localhost test]# if [ -r 1.sh ]; then echo OK; fi

OK

用法三、判斷用戶輸入是否爲數字

[root@localhost test]# cat 2.sh

#!/bin/bash

read -t 5 -p "Please input a number: " n

m=`echo $n | sed 's/[0-9]//g'`

if [ -n "$m" ]

then

echo "The character you input is not a number, Please retry."

else

echo $n

fi

用法四、判斷用戶輸入是否爲數字

[root@localhost test]# cat 2.sh

#!/bin/bash

read -t 5 -p "Please input a number: " n

m=`echo $n | sed 's/[0-9]//g'`

if [ -z "$m" ]

then

echo $n

else

echo "The character you input is not a number, Please retry."

fi

用法五、判斷指定字符串是否存在

[root@localhost test]# cat 3.sh

#!/bin/bash

if grep -q '^root:' /etc/passwd

then

echo "root exist."

else

echo "root not exist."

fi

[root@localhost test]# sh 3.sh

root exist.

用法六、多重判斷

[root@localhost test]# ll

總用量 16

-rw-r--r-- 1 root root  45 12月  9 19:32 1.sh

-rw-r--r-- 1 root root 182 12月  9 19:45 2.sh

-rw-r--r-- 1 root root  99 12月  9 19:56 3.sh

-rw-r--r-- 1 root root  79 12月  9 19:59 4.sh

[root@localhost test]# cat 4.sh

#!/bin/bash

# && 邏輯與  ||  邏輯或

if [ -d /tmp/ ] && [ -f 1.txt ]

then

echo OK

else

echo "not OK"

fi

[root@localhost test]# bash 4.sh

not OK

用法七、多重判斷

[root@localhost test]# ll

總用量 16

-rw-r--r-- 1 root root  45 12月  9 19:32 1.sh

-rw-r--r-- 1 root root 182 12月  9 19:45 2.sh

-rw-r--r-- 1 root root  99 12月  9 19:56 3.sh

-rw-r--r-- 1 root root  79 12月  9 19:59 4.sh

[root@localhost test]# cat 4.sh

#!/bin/bash

# -a 邏輯與  -o  邏輯或

if [ -d /tmp/ -o -f 1.txt ]then

echo OK

else

echo "not OK"

fi

[root@localhost test]# bash 4.sh

not OK


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章