版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010800708/article/details/84440263
1.if语句
#!/bin/bash
if condition
then
command1
command2
fi
2.if else 语句
#!/bin/bash
if condition
then
command1
command2
else
command1
command2
fi
3.if-elif-else语句
#!/bin/bash
if condition
then
command1
command2
elif condition1
then
command3
command4
elif condition2
then
command5
else
command6
fi
实例
#!/bin/bash
a=10
b=20
if [ $a -eq $b ]
then
echo "a==b"
elif [ $a -gt $b ]
then
echo "a > b"
elif [ $a -lt $b ]
then
echo "a<b"
else
"..."
fi
输出a<b
4.for语句
#!/bin/bash
for var in 1 3 6
do
echo " the value is $var"
done
输出
the value is 1
the value is 3
the value is 6
5.while循环
#!/bin/bash
var=1
while (( $var<=5 ))
do
echo $var
let var++
done
Bash let 命令,它用于执行一个或多个表达式,变量计算中不需要加上 $ 来表示变量
6.无限循环
#!/bin/bash
while :
do
command
done
for (( ; ; ))
7.until循环
until循环执行一系列命令直至条件为真时停止。 until循环与while循环在处理方式上刚好相反。 一般while循环优于until循环,但在某些时候—也只是极少数情况下,until循环更加有用
#!/bin/bash
until condition
do
command
done
8.case语句
相当于java中的switch语句
#!/bin/bash
read aNum
case $aNum in 1)
echo 'You have chosen 1';;
$aNum in 2)
echo 'You have chosen 2';;
$aNum in 3)
echo 'You have chosen 3';;
$aNum in *)
echo 'You did not enter a number between 1 and 3';;
esac
取值后面必须为单词in,每一模式必须以右括号结束。取值可以为变量或常数。匹配发现取值符合某一模式后,其间所有命令开始执行直至 ;;。
取值将检测匹配的每一个模式。一旦模式匹配,则执行完匹配模式相应命令后不再继续其他模式。如果无一匹配模式,使用星号 * 捕获该值,再执行后面的命令
case相当于switch
* 相当于default
9.跳出循环
在循环过程中,有时候需要在未达到循环结束条件时强制跳出循环,Shell使用两个命令来实现该功能:break和continue
break
#!/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! game over!"
break
;;
esac
done
continue
continue命令与break命令类似,只有一点差别,它不会跳出所有循环,仅仅跳出当前循环
#!/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"
;;
esac
done
case的语法和C family语言差别很大,它需要一个esac(就是case反过来)作为结束标记,每个case分支用右圆括号,用两个分号表示break