Shell logic judgment, branch statement (with case, Shell script study notes)

Logical syntax:

if [judgment condition] ; then

    ....

elif [judgment condition]; then

    ....

else

    ....

fi

(where fi is the end flag) 

Step on the pit reminder:

  • Before writing the conditional judgment in the curly brackets, there must be a space before and after. For example, the wrong way of writing: [ $a = $b] , the correct way of writing: [ $a = $b ]
  • Shell scripts are case-sensitive, and keywords such as if, elif, and echo cannot be written as IF, ELIF, and ECHO

Case 1:

Input a character, if the character is y, output right; if the character is n, input wrong; otherwise, output bad input

read -p "请输入一个字符:" c
if [ $c = 'y' ]; then
    echo "right"
elif [ $c = 'n' ]; then
    echo "wrong"
else
    echo "bad input"
fi

Case 2: Enter a number and determine whether it is greater than/equal/less than 5

read -p "请输入一个数字:" num
if [ $num -gt 5 ]; then
    echo "大于5"
elif [ $num -lt 5 ]; then
    echo "小于5"
else
    echo "等于5"
fi

 >> Tips: Number judgment operators are: -gt (greater than), -lt (equal to), -ge (equal to), -ge (greater than or equal to), -le (less than or equal to)

Case 3:

First judge whether the input directory exists, if it exists, use ls to display its files and directories, otherwise prompt: no such dir

read -p "输入一个目录名称:" dirname
if [ -d $dirname ]; then
    ls $dirname
else
    echo "no such dir"
fi

The effect is as follows:

Case 4: Application of branch statement and case

Input a character, if you input A or a, it will display 4, if you input B or b, it will display 3, if you input C or c, it will display 2, otherwise it will display "incorrect input"

read -p "please input a char: " c
case $c in
'A' | 'a')
   echo "4"
;;
'B' | 'b')
   echo "3"
;;
'C' | 'c')
   echo "2"
;;
*)
    echo "输入不正确"
;;
esac

operation result:

Case 5: Use while loop to calculate the sum of 1-100 numbers

i=1
res=0
while [ $i -le 100 ]
do
    res=$[$res+$i]
    i=$[$i+1]
done
echo $res

If you like it, welcome to like and collect~

Guess you like

Origin blog.csdn.net/calm_programmer/article/details/127829279