CentOS 7 Shell Scripting Lecture 10 if statement

Posted by himnbandit on Thu, 05 Dec 2019 12:51:16 +0100

Let's start with a simple script. First, remember that if and fi appear in pairs.

#Expression statement structure

if <Conditional expression> ;then
//instructions
fi

#Upper and lower statements are equivalent
if <Conditional expression> 
then
//instructions
fi

#Judge whether the input is yes, no other input operation
[root@promote ~]# cat testifv1.0.sh 
#!/bin/bash
read -p "please input yes or no: " input
if [ $input == "yes" ] ;then
echo "yes"
fi
#No direct return
[root@promote ~]# bash testifv1.0.sh 
please input yes or no: yes
yes
[root@promote ~]# 

When the condition expression of if statement is true, the subsequent statement is executed; when it is false, no operation is executed; the statement ends. Single branch structure.

Let's look at a slightly more complex code.

[root@promote ~]# cat testifv1.1.sh 
#!/bin/bash
read -p "please input yes or no: " input ;
if [ $input == "yes" -o $input == "y" ] 
then
echo "yes"
fi
[root@promote ~]# vim testifv1.2.sh 
[root@promote ~]# bash testifv1.2.sh 
please input yes or no: y
yes
[root@promote ~]# 
[root@promote ~]# bash testifv1.2.sh 
please input yes or no: n
[root@promote ~]# 

The if else statement is a two branch structure. There are two judgment structures, one is to judge whether the condition satisfies any condition, the other is to execute the statement directly if then block, and the other is to execute else block. Sentence structure is similar to single branch structure.

[root@promote ~]# cat testifv1.3.sh 
read -p "please input yes or no: " input ;
if [ $input == "yes" -o $input == "y" ] 
then
echo "yes"
else 
echo "no yes"
fi
[root@promote ~]# bash testifv1.3.sh 
please input yes or no: n
no yes
[root@promote ~]# bash testifv1.3.sh
please input yes or no: yes
yes
[root@promote ~]# 

It should be noted that else does not need to judge, but directly follows statements.

if else statement has more judging conditions, which can be called multi branch structure.

[root@promote ~]# cat testifv1.4.sh
#!/bin/bash
read -p "please input yes or no: " input
if [ $input == "yes" -o $input == "y" ]
then
echo "yes"
elif [ $input == "no" -o $input == "n" ]
then
echo "no"
else
echo "not yes and no"
fi
[root@promote ~]# 
[root@promote ~]# bash testifv1.4.sh
please input yes or no: yes
yes
[root@promote ~]# bash testifv1.4.sh
please input yes or no: y
yes
[root@promote ~]# vim testifv1.4.sh
[root@promote ~]# bash testifv1.4.sh
please input yes or no: no
no
[root@promote ~]# bash testifv1.4.sh
please input yes or no: n
no
[root@promote ~]# bash testifv1.4.sh
please input yes or no: ssss
not yes and no

Topics: vim