Branch statements
Single branch statement
if [ condition ];then
Command line...
fi
Example:
#!/bin/bash
if [ -f "" ]; then
echo "File exists"
fi
Double branch statement
if [ condition ];then
Command line...
else
Command line...
fi
Example:
#!/bin/bash
if [ -f "" ]; then
echo "File exists"
else
echo "The file does not exist"
fi
Multi-branch statement
if [ condition ];then
Command line...
elif [ condition ];then
Command line...
else
Command line...
fi
Example:
#!/bin/bash
if [ -f "" ]; then
echo "File exists"
elif [ -d "/etc" ]; then
echo "Directory exists"
else
echo "The file and the directory do not exist"
fi
case statement
Similar to branch statements, case is generally used to implement scripts with multiple choices (menu selection)
grammar:
case $ variable in
Mode 1)
# Execute when matching pattern 1
;;
Mode 2)
# Execute when matching pattern 2
;;
*)
# Default
;;
esac
Example:
#!/bin/bash
read -p "Input yes/no: " answer
case $answer in
yes|Yes|YES)
echo "You chose yes"
;;
no|No|NO)
echo "You chose no"
;;
*)
echo "Invalid input"
;;
esac
Loop statement
for loop
grammar:
for variables in list; do
# Circulation body
done
Example:
#!/bin/bash
for num in {1..10}
do
echo ${num}
done
While loop
grammar:
While [ condition ]
do
Order
done
Violent loop syntax
While [ condition ]
do
Order
done
Example: Use while loop to output 1..10
#!/bin/bash
num=1
while [ ${num} -le 10 ]
do
echo ${num}
let num++
done
Example: Calculate sums of 1-100 using while loop
#!/bin/bash
num=1
count=0
while [ ${num} -le 100 ]
do
let count+=num
let num++
done
echo ${count}
While reading the file
grammar:
while read variable
do
Commands/Content
done <file path
Example:
#!/bin/bash
filename=/etc/passwd
while read line
do
echo ${line}
done <${filename}
Loop control statement
break
break is used to terminate the current loop and will not continue to run the remaining loop.
Example:
#!/bin/bash
for i in {1..10}; do
if [ $i -eq 5 ]; then
break
fi
echo "Current value: $i"
done
continue
Continue is used to terminate this loop and enter the next loop
Example:
#!/bin/bash
for i in {1..5}; do
if [ $i -eq 3 ]; then
Continue continue
fi
echo "Current value: $i"
done