shell script seven: if structure conditional sentence knowledge and Practice

7, Knowledge and practice of if structure conditional sentence

(1) if conditional single and double branch syntax

1. Single branch
 if condition
   then
   instructions
fi
 2. Bifurcate
 if condition
   then
   instructions
else
   Instruction set 2
fi

(2) if conditional multi branch statement

1. Structure of statement

if condition 1
   then
   Instruction 1
 elif condition 2
   then
   Instruction 2
 elif condition 3
   then
   Instruction 3
else
   Instruction 4   
fi 

2. Example: determine whether the directory exists

If no directory exists/backup,Then create.
[root@centos6-kvm3 scripts]# cat 07-01.sh
#!/bin/bash
path="/backup"
[ -d $path ] || mkdir $path -p
if [ -d $path ]
then
   :(A colon means nothing)
else
  mkdir $path -p
fi

if [ !-d $path]
then
  mkdir $path -p
fi
[root@centos6-kvm3 scripts]#

3. Example: judge server memory size

Development shell The script determines whether the memory is sufficient. If it is less than 100, the prompt is insufficient. If it is greater than 100, the prompt is sufficient.
[root@centos6-kvm3 scripts]# cat 07-02.sh 
#!/bin/bash
mem=`free -m | awk 'NR==3{print $NF}'`
if [ $mem -lt 100 ]
then
   echo "Not enough memory!"
else
   echo "Enough memory!"
fi
[root@centos6-kvm3 scripts]# 

4. Example: judge the size of two integers

[root@centos6-kvm3 scripts]# cat 07-03.sh
#!/bin/bash
read -p "Please enter two integers:" a b
expr $a + $b + 1 &>/dev/null
if [ $? -ne 0 ]
then
   echo "Please enter two integers."
   exit 0
fi
if [ -z "$b" ]
then
  echo "Please enter two integers."
  exit 1
fi

if [ $a -lt $b ]
then
   echo "$a less than $b"
elif [ $a -gt $b ]
then
   echo "$a greater than $b"
else
   echo "$a Be equal to $b"
fi
//If the parameter transfer method is used:
[$# -ne 2] judge whether there are two parameters.

5. Example: print an installation menu

[root@centos6-kvm3 scripts]# cat 07-04.sh
#!/bin/bash
cat <<EOF
1.install lamp
2.install lnmp
3.exit
EOF
read -p "Please enter a number{1|2|3}: " n
expr $n + 2 &>/dev/null
if [ $? -ne 0 ]
then
   echo "usage:$0{1|2|3}"
   exit 0
fi

if [ $n -eq 1 ]
then
   echo "install lamp"
elif [ $n -eq 2 ]
then
   echo "install lnmp"
elif [ $n -eq 3 ]
then
   echo "exit"
else
   echo "usage:$0{1|2|3}"
fi
[root@centos6-kvm3 scripts]# 


Keywords: Linux less shell

Added by crishna369 on Wed, 29 Apr 2020 17:46:38 +0300