Bash控制结构

时间:2022-08-04 21:11:56

1. if-else语句

#!/bin/bash

#if ... fi 语句;
if [ $a != $b ]
then
echo "a != b"
fi #if ... else ... fi 语句;
if [ $a == $b ]
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi #if ... elif ... else ... fi 语句;
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 "None of the condition met"
fi

2. case-esac语句

#!/bin/bash

read -p "Please input a number" aNum
case $aNum in
) echo 'You select 1'
;; #不要忘记加上这一行
) echo 'You select 2'
;;
) echo 'You select 3'
;;
) echo 'You select 4'
;;
*) echo 'You do not select a number
between to '
;;
esac

3. for循环

#!/bin/bash

#for循环一般格式为:
#for 变量 in 列表
#do
# command1
# command2
# ...
# commandN
#done
#列表是一组值(数字、字符串等)组成的序列,每个值通过空格分隔。每循环一次,就将列表中的下一个值赋给变量。
#in 列表是可选的,如果不用它,for 循环使用命令行的位置参数。 #for loop in
for loop in tt kk
do
echo "The value is: $loop"
done
#The value is:
#The value is:
#The value is: tt
#The value is:
#The value is:
#The value is: kk num=
for str in 'This is a string'
do
num=`expr $num + `
echo $str $num #-->This is a string ;只执行一次
done

4. while循环

#!/bin/bash   

COUNTER=
while [ $COUNTER -lt ]
do
COUNTER=`expr $COUNTER + `
done

5. until循环

#!/bin/bash   

#until 循环执行一系列命令直至条件为 true 时停止。until 循环与 while 循环在处理方式上刚好相反。一般while循环优于until循环,但在某些时候,也只是极少数情况下,until 循环更加有用。  

a=
until [ ! $a -lt ]
do
echo $a #-->
a=`expr $a + `
done

6. break,continue跳出循环