table of Contents
(1) if else conditional statement
(1) if else conditional statement
The following example judges whether two variables are equal:
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
elif [ $a -gt $b ]
then
echo "a is greater than b"
elif [ $a -lt $b ]
then
echo "a is less than b"
else
echo "No conditions are met"
be
(2) for loop statement
Output the numbers in the current list in order
for num in 1 2 3 4 5
do
echo "The value is: $num"
done
#The value is: 1
#The value is: 2
#The value is: 3
#The value is: 4
#The value is: 5
Sequence the characters in the string
for str in 'This is a string'
do
echo $str
done
#Output:This is a string
Infinite loop
while true
do
command
done
(3) until loop statement
The until loop executes a series of commands until the condition is true and stops.
#!/bin/bash
a=0
until [ ! $a -lt 10 ]
do
echo $ a
a=`expr $a + 1`
done
(4) case branch statement
Each branch must end with a closing parenthesis. The value in the right parenthesis can be a variable or a constant. After matching a branch, all commands are executed to;;
echo'Enter a number between 1 and 4:'
echo'The number you entered is:'
read aNum
case $aNum in
1) echo'you chose 1'
;;
2) echo'you chose 2'
;;
3) echo'you chose 3'
;;
4) echo'you chose 4'
;;
*) echo'You did not enter a number between 1 and 4'
;;
esac
#!/bin/sh
site="runoob"
case "$site" in
"runoob") echo "Novice Tutorial"
;;
"google") echo "Google 搜索"
;;
"taobao") echo "淘宝网"
;;
esac
(5) break out of the loop
break terminates the execution of all subsequent loops, continue only jumps out of the current loop
The following example enters an endless loop until the user enters a number greater than 5, and enters break to jump out of this loop.
#!/bin/bash
while :
do
echo -n "Enter a number between 1 and 5:"
read aNum
case $aNum in
1|2|3|4|5) echo "The number you entered is $aNum!"
;;
*) echo "The number you entered is not between 1 and 5! The game is over"
break
;;
esac
done
(6) continue out of the loop
break terminates the execution of all subsequent loops, continue only jumps out of the current loop
#!/bin/bash
while :
do
echo -n "Enter a number between 1 and 5: "
read aNum
case $aNum in
1|2|3|4|5) echo "The number you entered is $aNum!"
;;
*) echo "The number you entered is not between 1 and 5!"
continue
echo "game over" #sentence echo "game over" will never be executed.
;;
esac
done