一、分支逻辑
1、if
if condition1
thencommand1
elif condition2
then command2
elsecommandN
fi
echo please input first number
read a
echo please input second number
read bif [ $a -eq $b ]
thenecho "equal"
elif [ $a -gt $b ]
thenecho "the first is greater than the second"
elseecho "the first is less than the second"
fi
2、case
匹配成功后执行相应命令,执行结束后即退出,没有匹配到则执行*对应的命令,相当于else。
case value in
value1)command1;;
value2)command2;;
*)command2;;
esac
echo please input your choice:1~4
read choicecase $choice in
1)echo your choice is 1;;
2)echo your choice is 2;;
3)echo your choice is 3;;
4)echo your choice is 4;;
*)echo illegal choice;;
esac
二、循环逻辑
1、for
for value in value1 value2 ... valueN
docommands
done
for value in 1 2 3 4 5
do echo "This value is $value"square=`expr $value \* $value`echo "It's square is $square"
done
2、while和until
while condition
docommands
done
①对于条件,如果使用中括号[],应该用-eq、-gt这样的
如果使用两对小括号,则可以使用>、>=这样的
②使用let命令操作变量时,无需使用$
如let sum+=i的等价表达是sum=`expr $sum + $i`
③去掉condition则是无限循环
④把while换成until即为until循环,区别在于:
while循环当condition为真时执行循环;until执行循环直到condition为假。
echo This program calculates the sum from 1 to N
echo Now please input the value of N
read Ni=1
sum=0
while(( i<=N ))
doecho "Now the number of i is $i"let sum+=ilet i++
doneecho "the sum from 1 to N is $sum"
3、break和continue
break跳出循环,continue结束当前循环,进入下一次循环。
i=5while((i<10))
doj=3while((j>0))doecho "i is $i, j is $j"let j--#break#break 2 # 2表示跳出两层循环,在这个例子中会直接跳出最外层循环#continueecho This is after continuedonelet i++
done