Theory + experiment · conditional statements of Shell programming

Theory + experiment · conditional statements of Shell programming

Condition test operation

test command

Test whether the expression is true. If it is true, return 0; otherwise, return other values

Format 1:test conditional expression

Format 2:[conditional expression]

Common test operators

-d: test whether it is a directory

-e: test whether the directory or file exists

-f: test whether it is a file

-r: test whether the current user has permission to read

-w: test whether the current user has permission to write

-x: test whether the current user has permission to execute

Document testing

[operator file or directory]

Common test operators
[root@localhost ~]# [ -d /dev/cdrom ]

[root@localhost ~]# echo $?

0                        ===>Returning 0 means the condition is true

[root@localhost ~]# [ -d /dev/cdrom/Server ]

[root@localhost ~]# echo $?  

1                         ===>If 1 is returned, the condition is invalid

[root@localhost ~]# [-d /dev/cdrom]&&echo "yes" ===> logical and the meaning of "and"

YES

Integer value comparison

[integer 1 operator integer 2]

Common test operators

-eq: equal

-ne: not equal

-gt: greater than

-lt: less than (Lesser Than)

-le: less than or equal

-ge: greater or equal

Common test operators
[root@localhost ~]# who | ec -l

6

[root@localhost ~]# [$(who | wc-l) -gt 5]&&echo "too many. ====> Whether the number of users >5

Too Many.

[root@localhost ~]#  [$(who | wc-l) -gt 10]&&echo ">=10. ===> Whether the number of users is > =10

Common test operators

[root@localhost ~]#  FreeCC=$(free -m | grep "Mem:" | awk '{print $6}')

[root@localhost ~]#  [$freecc -lt 1024]& & echo ${freecc}mb = = = > is free memory <1024mb

588MB

string comparison

Format 1 [string 1 = string 2]

[string 1! = string 2]

Format 2 [-z string]

Common test operators

=: same string content

! =: String content is not valid,! The sign means the opposite

-z: the string content is empty

Common test operators
[root@localhost ~]#  echo $LANG 

zh_CN.UTF-8

[root@localhost ~]#  [$lang! = "en.us"]&&echo "not en.us" ===> test the current locale

Not en.US
[root@localhost ~]#  read -p "overwrite existing file (yes/no) ACK

Overwrite existing file (yes/no)? yes

[root@localhost ~]#  [$ack = "yes"]&&echo "overwrite" ===> test whether the read string is yes

cover

Logic test

Format 1: [expression 1] operator [expression 2]

Format 2: command 1 operator command 2

Common test operators

-a or & &: logical and the meaning of "and"

-o or |: logical or, meaning of "or"

!: Logical no

[root@localhost ~]# [ -d /etc ] && [ -r /etc ] && echo "You can open it"

[root@localhost ~]#  [ -d /etc ] || [ -d /home ]&&echo "ok"

Structure of if statement

Single branch structure

if    Condition test operation                       if    disk space used>80%

    then    Command sequence                        then    Alarm

fi                                     fi

Double branch structure

if    Condition test operation                       if    80 Whether the port is listening

    then    Command sequence 1                        then    Site service is already running
    else    Command sequence 2                        else    start-up htpd service
fi                                     fi

Multi branch structure

if    Condition test operation 1                                                     if    Score 85~100 between

    then    Command sequence 1                                                       then    Judged as excellent

elif     Condition test operation 2                                                 elif    Score is 70~84 between

    then Command sequence 2                                                          then    Qualified

else                                                                              else

    Command sequence 3                                                                   Judged as unqualified

fi                                                                                   fi

Application example of if statement

Single branch if statement

Determine the mount point directory. If it does not exist, it will be created automatically

[root@locahost ~]# cat chkmountdir.sh

#!/bin/bash

MOUNT_DIR="/dev/cdrom"

if[ ! -d $MOUNT_DIR]  ===>Execute when directory does not exist

    then

    mkdir -p $MOUNT_DIR

fi

Double branch if statement

Judge whether the target host is in inventory and display the test results

[root@localhost ~]# cat pinghost.sh

#!/bin/bash

ping -c 3 -i 0.2 -W 3 $1 &> /dev/null  ===>"-c"Three test packages "-i"Interval 0.2 second "-W"Timeout 3 seconds

if [ $? -eq 0 ]

  then                                                      ===>judge ping Test results of command,Give the impassability prompt respectively

    echo "Host $1 is up."         

  else

    echo "Host $1 is down."

fi

Multi branch if statement

Judge the score range and divide it into three grades: excellent, qualified and unqualified

[root@localhost ~]# cat gradediv.sh

#!/bin/bash

read -p "Please enter your score(0-100):" GRADE

if [ $ake -ge 85 ] && [ $ake -le 100 ]                   ===>Judge the range of scores,Give different grading results

then

    echo "$GRADE branch,excellent!"

elif [ $ake -ge 70 ] && [ $ake -le 84 ]

    then

echo "$GRADE branch,qualified!"

else

  echo "$GRADE branch,Unqualified!"

fi

case statement structure

case multi branch structure

case variable value in

Mode 1)

Command sequence 1

​ ;;

Mode 2)

Command sequence 2

​ ;;

*)

Default command sequence

esca

case statement application instance

case multi branch statement

[root@localhost ~]# cat hitkey.sh

#!/bin/bash

read -p "Please enter a character,And press Enter Key confirmation:" KEY

case $KEY in

[a-z]|[A-Z])           ===>Match any letter

    echo "The hour letter you entered."

    ;;

[0-9])                     ===>Match any number

    echo "The hour number you entered."

    ;;

*)                           ===>Match any character

    echo "You entered a space, function key, or other control character."

esac

Small experiment = = = > for reference only, there is room for optimization

#!/bin/bash
#Stone scissors paper games
num=`echo $[$RANDOM%3+1]`
read -p "Please enter the stone(1),scissors(2),cloth(3):" shoushi

if [ $shoushi -eq 1 ]
 then

   if [ $num -eq 1 ]
    then
    echo "What the computer produces is a stone,draw"
   elif [ $num -eq 2 ]
    then
    echo "The computer came out with scissors,You won"
   else echo "The computer produces cloth,You lost"
   fi

 elif [ $shoushi -eq 2 ]
   then

   if [ $num -eq 1 ]
    then
    echo "What the computer produces is a stone,You lost"
   elif [ $num -eq 2 ]
    then
    echo "The computer came out with scissors,draw"
   else echo "The computer produces cloth,You won"
   fi

 else
fi
#!/bin/bash
#Enter the final within 10 seconds of the speed race, divided into men's group and women's group

read -p "Please enter your 100 meter race result:" miao
read -p "Please enter your gender(male or female):" xing


if [ $xing = male ]
    then
      echo "Men's group"

  if [ $miao -ge 0 ]&&[ $miao -le 10 ]
    then
      echo "Pass the test"
    else
      echo "Unqualified performance,Be eliminated."
  fi

  elif [ $xing = female ]
    then
      echo "Women's group"

  if [ $miao -ge 0 ]&&[ $miao -le 10 ]
    then
      echo "Pass the test"
    else
      echo "Unqualified performance,Be eliminated."
  fi

  else
      echo "Please enter the correct information"
fi

Tags: cloud computing shell

Posted by FangerZero on Mon, 30 May 2022 04:30:06 +0530