if-else语句
#!/bin/bash
#3种ifelse形式,以 fi 来结尾闭合 if,fi 就是 if 倒过来拼写
<strong>#if ... fi 语句;
#if ... else ... fi 语句;
#if ... elif ... else ... fi 语句;</strong>
#if ... fi 语句;
a=10
b=-5
#if ... fi 语句;
if [ $a != $b ] #在[]和!=前后要有一空格,且必须有[](除了用test)
then #then需要另启一行,不能与if在同一行(除了加;)
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
#if ... else 语句也可以写成一行,以命令的方式来运行,
if test $[2*3] -eq $[1+5]; then echo 'The two numbers are equal!'; fi;
#if ... else 语句也经常与 test 命令结合使用
#test 命令用于检查某个条件是否成立,与方括号([ ])类似
case-esac语句
#!/bin/bash
#case ... esac与其他语言中的 switch ... case 语句类似,是一种多分枝选择结构。
<strong>#关键字与,case-in-;;-esac</strong>
echo 'Input a number between 1 to 4'
echo -e 'Your number is:\c'
read aNum
case $aNum in
1) echo 'You select 1'
;;
2) echo 'You select 2'
;;
3) echo 'You select 3'
;;
4) echo 'You select 4'
;;
*) echo 'You do not select a number between 1 to 4'
;;
esac
for循环
#!/bin/bash
#for循环一般格式为:
#for 变量 in 列表
#do
# command1
# command2
# ...
# commandN
#done
#列表是一组值(数字、字符串等)组成的序列,每个值通过空格分隔。每循环一次,就将列表中的下一个值赋给变量。
#in 列表是可选的,如果不用它,for 循环使用命令行的位置参数。
#for loop in 1 2 3 4 5
for loop in 1 2 tt 4 5 kk
do
echo "The value is: $loop"
done
#The value is: 1
#The value is: 2
#The value is: tt
#The value is: 4
#The value is: 5
#The value is: kk
num=0
for str in 'This is a string'
do
num=`expr $num + 1`
echo $str $num #-->This is a string 1 ;只执行一次
done
while循环
#!/bin/bash
COUNTER=0
while [ $COUNTER -lt 3 ]
do
COUNTER=`expr $COUNTER + 1`
done
echo COUNTER=$COUNTER #--》COUNTER=3
#while循环可用于读取键盘信息
echo 'type <CTRL-D> to terminate'
echo -n 'enter your most liked film: '
count=0
while read FILM
do
echo "Yeah! great film the $FILM"
count=`expr $count + 1`
if [ $count -gt 0 ]
then
break
fi
done
#输出
#type <CTRL-D> to terminate
#enter your most liked film: 3
#Yeah! great film the 3
until循环
#!/bin/bash
#until 循环
#until 循环执行一系列命令直至条件为 true 时停止。until 循环与 while 循环在处理方式上刚好相反。一般while循环优于until循环,但在某些时候,也只是极少数情况下,until 循环更加有用。
a=0
until [ ! $a -lt 5 ]
do
echo $a #--> 0 1 2 3 4 5
a=`expr $a + 1`
done
break,continue跳出循环
#!/bin/bash
#跳出循环 break,continue
for var1 in 1 2 3
do
for var2 in 0 5
do
if [ $var1 -eq 2 -a $var2 -eq 0 ]
then
break 2 #表示跳出第 2 层循环。默认为1
else
echo "$var1 -- $var2"
fi
done
done
#1 -- 0
#1 -- 5
NUMS="1 2 3 4 5"
for NUM in $NUMS
do
Q=`expr $NUM % 2`
if [ $Q -eq 0 ]
then
echo "Number is an even number!!"
continue
fi
echo "Found odd number"
done
#Found odd number
#Number is an even number!!
#Found odd number
#Number is an even number!!
#Found odd number