Bash條件判斷


bash編程之:條件判斷,判定后續操作的前提條件是否滿足,

bash編程之: 條件判斷常用類型:

  整數測試:比較兩個整數誰大誰小,是否相等;

    二元測試:

      num1 操作符 num2

      -eq: 等於

      -ne: 不等於

      -le:小於等於

      -ge:大於等於 

      -lt:小於

      -gt: 大於

  字符測試:比較兩個字符串是否相等;

    雙目錄

           >:          大於

           <:          小於

           ==:             等於,等值比較

           =~:             左側是字符串,右側是一個模式,判定左側的字符串能否被右側的模式所匹配;通常只[[]]中使用,模式中可以使用行首、行尾錨定符;但模式不要加引導

           !=, <>:     不等於

    單目錄

           -n 字符串:  字符串是否不空,不空為真,空則為假

           -z 字符串:  字符串是否為空,空則為真,不空則假

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
[root@demo scripts] # stringA="root"
[root@demo scripts] # stringB="hello"
[root@demo scripts] # [ "$stringA" == "$stringB" ]
[root@demo scripts] # echo $?
1
[root@demo scripts] # stringB="root"
[root@demo scripts] # [ "$stringA" == "$stringB" ]
[root@demo scripts] # echo $?
0
[root@demo scripts] # userName=root
[root@demo scripts] # [[ `grep "^$userName\>" /etc/passwd | cut -d: -f7` =~ sh$ ]]
[root@demo scripts] # echo $?
0
[root@demo scripts] # userName=bin
[root@demo scripts] # [[ `grep "^$userName\>" /etc/passwd | cut -d: -f7` =~ sh$ ]]
[root@demo scripts] # echo $?
1
[root@demo scripts] # [ -n userName ]
[root@demo scripts] # echo $?
0

  文件測試:測試某個文件是否具有讀權限、寫權限、執行權限等;

    單目測試:

      -e file :         測試文件是否存在

      -a file :         測試文件是否存在

      -f file :         測試是否為普通文件

      -d     :            測試是否為目錄文件

      -b somefile :     測試文件是否存在並且是否為一個塊設備文件

      -c somefile :     測試文件是否存在並且是否為一個字符設備文件

      -h|-L somefile :     測試文件是否存在並且是否為符號鏈接文件

      -p somefile :     測試文件是否存在並且是否為管道文件:

      -S somefile :     測試文件是否存在並且是否為套接字文件:

      -r somefile:      測試其有效用戶是否對此文件有讀取權限

      -w somefile:      測試其有效用戶是否對此文件有寫權限

      -x somefile:      測試其有效用戶是否對此文件有執行權限

      -s somefile:      測試文件是否存在並且不空

     雙目測試:

      file1 -nt file2 : 測試file1是否比file2更 新一些

      file1 -ot file2 : 測試file1是否比file2更 老一些

      file1 -ef file2 :  測試file1和file2是否引用同一個文件   

bash編程之:邏輯運算:

    與運算:

      真 && 真 = 真 

      真 && 假 = 假

      假 && 真 = 假

      假 && 假 = 假

    或運算:

      真 || 真 = 真 

      真 || 假 = 真

      假 || 真 = 真

      假 || 假 = 假

    非運算:

      !真 = 假

      !假 = 真

bash編程之:組合條件測試

    與:條件1 &&條件2

      條件1為假,則最終結果一定為假,否則,條件2不予執行

      條件1為真,則最終條件結果決於后面條件,因此,條件2必須執行

    或:條件1 ||條件2

      條件1為真,則最終結果一定為真,否則,條件2不予執行

      條件1為假,則最終條件結果決於后面條件,因此,條件2必須執行

    非: 

      與的優先級大於或,或的優先級大於非

bash編程之:條件測試方法

     test 表達式

     [ 測試表達式 ]

     [[ 測試表達式 ]]

bash編程之:if條件判斷使用:

    單分支:

       if 條件; then

          分支1;

       fi

    雙分支:

        if 條件; then

         分支1;

        else 

         分支2;

        fi

    多分支:

        if 條件; then

          分支1;

        elif 條件2; then 

          分支2;

        elif 條件3; then 

          分支3;

           ...

        else 

          分支n;

        fi

bash編程之:命令引用:

  1.引用命令的執行結果:使用`COMMAND`或$(COMMAND)

  2.引用命令執行是否成功的狀態結果:一定是直接執行命令,此時需要執行結果重定向至/dev/null

bash編程之:腳本自動退出

  exit [n] 

        0表示成功(Zero - Success)

        非0表示失敗(Non-Zero  - Failure)

        2表示用法不當(Incorrect Usage)

        127表示命令沒有找到(Command Not Found)

        126表示不是可執行的

 

練習:

 

  1.寫一腳本,實現如下功能;

   1、讓用戶通過鍵盤輸入一個用戶名

   2、如果用戶存在,就顯示其用戶名和UID;

   3、否則,就顯示用戶不存在;

1
2
3
4
5
6
7
8
#!/bin/bash
#
read -p "please input userName: " userName
if grep "^$userName\>" /etc/passwd & > /dev/null ; then
   echo "$userName :`id -u $userName`" ;
else
    echo "$userName is not OK !!" ;
fi

  2.寫一腳本,實現如下功能;

  1、讓用戶通過鍵盤輸入一個用戶名,如果用戶不存在就退出;

  2、如果用戶的UID大於等於500,就說明它是普通用戶;

  3、否則,就說明這是管理員或系統用戶;

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash
#
read -p "please input userName: " userName
if ! grep "^$userName\>" /etc/passwd & > /dev/null ; then
   echo "Can you speak Chinese" ;
   exit 62
fi
   i=` id -u $userName`;
if [ $i - ge 500 ]; then
   echo "The $userName is putong user" ;
else
   echo "The $userName is root user" ;
fi

  3.寫一腳本,實現如下功能;

  1、讓用戶通過鍵盤輸入一個用戶名,如果用戶不存在就退出;

  2、如果其UID等於其GID,就說它是個"good guy"

  3、否則,就說它是個“bad guy”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/bin/bash
#
read -p "please input userName: " userName
if ! grep "^$userName\>" /etc/passwd & > /dev/null ; then
  echo "Can you speak Chinese" ;
exit 62
fi
i=` id -u $userName`
g=` id -g $userName`
if [ $i - eq $g ]; then
  echo "$userName is good guy" ;
else
  echo "$userName is bad guy" ;
fi

4.擴展題3:判斷當前系統的所有用戶是goodguy 還是bad guy;

1
2
3
4
5
6
7
8
9
10
11
#!/bin/bash
#
for userName in ` cut -d:-f1 /etc/passwd `; do
   i=` id -u $userName`
   g=` id -g $userName`
   if [ $i - eq $g ]; then
     echo "$userName is good guy" ;
   else
     echo "$userName is bad guy" ;
   fi
done

 5.寫一個腳本,實現如下功能;

  1、添加10個用戶stu1-stu10;但要先判斷用戶是否存在;

  2、如果存在,就用紅色顯示其已經存大在

  3、否則,就添加此用戶;並綠色顯示;

  4、最后顯示一共添加了幾個用戶;

1
2
3
4
5
6
7
8
9
10
#!/bin/bash
#
for i in {1..10}; do
   if grep "^stu$i\>" /etc/passwd &> /dev/null ; then
     echo -e "\033[31mstu$i\033[0m is sunflly"
   else
     useradd stu$i&& echo -e "useradd \033[32mstu$i\033[0m is suefully"
   fi
done
echo "Add $UserCount users."

6.200以為所有3的整數倍正整數的和;

1
2
3
4
5
6
7
8
#! /bin/bash
#
declare -i sum =0
for i in {1..200}; do
   if [ $i%3 = 0 ]; then
     let sum =$ sum +$i;
   fi
done

7.讓用戶指定一個文件,判定:如果文件有空白行,就顯示空白行數;否則,就說明無空白行;

1
2
3
4
5
6
7
8
9
#! /bin/bash
#
read -p "Enter a file path: " filename
if grep "^&" $filename &> /dev/null ; then
   linesCount=` grep "^&" $filename | wc -l`
   echo "$filename has $linesCount space lines."
else
   echo "$filename hace no space lines."
fi

8.判定兩個數孰大孰小,整數是通過命令行參數傳遞而來;

1
2
3
4
5
6
7
#! /bin/bash
#
if [ $1 -gt $2 ]; then
   echo "The max num is $1."
else
   echo "The max num is $2."
fi

9.判定所有用戶是否擁有可登錄shell;

1
2
3
4
5
6
7
8
9
#! /bin/bash
#
for userName in ` cut -d: -f1 /etc/passwd `; do
     if [[ ` grep "^$userName\>" /etc/passwd | cut -d: -f7` =~ sh$ ]]; then
         echo "login user: $userName"
     else
         echo "nologin user: $userName"
     fi
done

10.寫一腳本,實現如下功能:

    1、讓用戶交互式輸入一個用戶名,先判斷用戶是否存在;不存在則以7退出

    2、判斷用戶的shell是否為/bin/bash;如果是,則顯示為"bash user.",退出碼為0,否則顯示為"Not bash user.",退出碼為1。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#! /bin/bash
#
read -t 3 -p "Enter Input UserName " userName
  
if ! id $userName &> /dev/null ; then
     echo "No such user."
     exit 7
fi
  
userShell=` grep "^$userName\>" /etc/passwd | cut -d: -f7`
  
if [[ "$userShell" == "/bin/bash" ]]; then
     echo "bash user."
     returnValue=0
else
     echo "Not bash user."
     returnValue=1
fi
  
exit $returnValue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#! /bin/bash
#
read -t 5 -p "Enter Input UserName: " UserName
if [[ $UserName != ` grep "^$UserName"  /tmp/passwd | cut -d: -f1` ]]; then
     echo "No Such $UserName."
     exit 7
elif [[ ` grep "^$UserName"  /tmp/passwd | cut -d: -f7` =~ sh$ ]]; then
     
        echo "$UserName is bash user."
         exit 0
else
         echo "$UserName Not bash user."
         exit 1
fi

11.寫一個腳本,實現如下功能;

      1、顯示如下菜單:

           CPU) show cpu info;

           men) show memory info;

           quit) quit

           Enter your option:

      2、如果用戶選擇CPU,則顯示文件/proc/cpuinfo的信息;

      3、如果用戶選擇mem,則顯示文件/proc/meminfo的信息;

      4、如果用戶選擇quit,則退出,且退出碼為5;

      5、如果用戶鍵入其它字符,則顯示未知選項,請重新執行腳本;退出碼為6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#! /bin/bash
#
echo "CPU)Show Cpu Info: "
echo "Men)Show Memory info: "  
echo "quit)quit "
  
read -t 5 -p "Enter your Chooise Option:" Chooise
  
if [[ $Chooise == CPU ]]; then
         echo ` cat /proc/cpuinfo `
elif [[ $Chooise == Men ]]; then
         echo ` cat /proc/meninfo `
else
         exit 6
fi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#! /bin/bash
#
cat <<EOF
cpu) print cpu infomation
men) print memory infomation
quit) Quit
EOF
      
returnValue=0
  
read -t 3 -p "Enter your option " userOption
userOption=` echo $userOption | tr 'a-z' 'A-Z' `
  
if [[ $userOption == "CPU" ]]; then
     cat /proc/cpuinfo
elif [[ $userOption == "MEM" ]]; then
     cat /proc/meminfo
elif [[ $userOptin == "QUIT" ]]; then
     echo "Quit"
     returnValue=6
else
     echo "Unkown Option"
     returnValue=7
fi
  
exit $returnValue

  12.寫一個腳本,實現如下功能;

    1.分別復制/var/log/下的文件至/tmp/log目錄中;

    2.復制目錄時,使用cp -r;

    3.復制文件時,使用cp;

    4.復制鏈接文件時,使用cp -d;

    5.余下的類型,使用cp -a;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#! /bin/bash
#
targetDir= '/tmp/logs'
 
[ -e $targetDir ] || mkdir $targetDir
for fileName in /var/log/ *; do
   if [ -d $fileName ]; then
     copyCommand= 'cp -r'
   elif [ -f $fileName ]; then
     copyCommand= 'cp'
   elif [ -h $fileName ]; then
     copyCommand= 'cp -d'
   else
     copuCommand= 'cp -a'
   fi
 
   $copyCommand $fileName $targetDir
done

  13.寫一個腳本,實現如下功能;

    1.其使用形式如下所示;

      script.sh{start|stop|restart|status}

    2.如果參數為空,則顯示幫助信息,並退出腳本;

    3.如果參數為start,則創建空文件/tmp/scipt,並顯示starting script successfully;mp

    4.如果參數為stop,則刪除文件/tmp/script,並顯示stop script succesfully;

    5.如果參數為restart,則刪除文件/tmp/script並重新創建,而后顯示Rstart script successfully;

    6.如果參數為status,那么

      如果文件/tmp/script存在,則顯示Script is running...,否則,則顯示Script is stoped;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#! /bin/bash
#
Dir= /tmp/script
 
if ! [[ $1 =~ [startstoprestartstatus] ]]; then
   echo "script.sh{start|stop|restart|status"
elif [ $1 == start ]; then
   mkdir $Dir && echo "Starting Script Successfully.."
elif [ $1 == stop ]; then
   rm -rf $Dir && echo "Stop Script Successfully..."
elif [ $1 == restart ]; then
   rm -rf $Dir && mkdir $Dir &&  echo "Stop Script Successfully..."
elif [ $1 == status ]; then
   if [ -e $Dir ]; then
     echo "Script is running..."
   else
     echo "Script is stoped..."
   fi
fi

  14.寫一個腳本,實現如下功能;

    1.使用形式如下:userinfo.sh -u username [-v {1|2}]

    2.-u選項用於指定用戶,而后腳本顯示用戶UID和GID;

    3.如果同時使用了-v選項;

      -v后面的值如果是1,則額外顯示用戶的家目錄路徑;

      -v后面的值如果是2,則額外顯示用戶的家目錄路徑和shell;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#! /bin/bash
#
 
[ $ # -lt 2 ] && "Too less argements,quit..." && exit 5
 
if [[ "$1" == "-u" ]]; then
   userName= "$2"
   shift 2
fi
 
if [ $ # -ge 2 ] && [ "$1" == "-v" ]; then
   verFlag=$2
fi
 
# echo $userName &verFlag
 
verFlag=${verFlag:-0}
if [ -n $verFlag ]; then
   if ! [[ $verFlag =~ [012] ]]; then
     echo "Wrong Parameter."
     echo "Usage: `basename $0` -u userName -v {1|2}"
     exit 4
   fi
fi
 
if [ $verFlag - eq 1 ]; then
   grep "^$userName" /etc/passwd | cut -d: -f1,3,4,6
elif [ $verFlag - eq 2 ]; then
   grep "^$userName" /etc/passwd | cut -d: -f1,3,4,6,7
else
   grep "^$userName" /etc/passwd | cut -d: -f1,3,4
fi

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM