if-then语句:
if command
then commands
fi
该语句首先执行if后的命令,如果该命令的退出状态码是0,则then后的语句执行。
例子:
#!/bin/bash
user=hgy
if grep $user /etc/passwd
then
echo "this is my first command"
echo "this is my second command"
echo "dafhfhjdshkjahsjjkf"
ls -a /home/$user
fi
if-then-else 语句 :
if command
then
commands
else
commands
fi
例子:
#!/bin/bash
user=hgy
if grep $user /etc/passwd
then
echo "The bash files for user $user are:"
ls -a /home/$user
echo
else
echo "The user $testuser does not exist on this system."
echo
fi
嵌套if
例子:
#!/bin/bash
user=hgy
if grep $user /etc/passwd
then
echo "the user $user exists on this system"
else
echo "the user $user does not exist on this system"
if ls -d /home/$user/
then
echo "however $user has a diretory"
fi
fi
------------------------------------------------------------------------------------------
if command1
then
commands
elif command2
then
more commands
fi
上述例子可以改写为:
#!/bin/bash
user=hgy
if grep $user /etc/passwd
then
echo "the user $user exists on this system"
elif ls -d /home/$user/
then
echo "the user $user does not exist on this system"
echo "however $user has a diretory"
fi
test命令提供了在if-then语句中测试不同条件的途径。如果test命令中列出的条件成立, test命令就会退出并返回退出状态码0。这样if-then语句就与其他编程语言中的if-then语句 以类似的方式工作了。如果条件不成立,test命令就会退出并返回非零的退出状态码,这使得 if-then语句不会再被执行。
if test condition
then
commands
fi
也可以使用如下形式代替:
if [ condition ]
then
commands
fi
数值比较:
eq --等于 ge --大于等于 gt --大于 le --小于等于 lt --小于 ne --不等于
字符串比较:
= != < > -n str --str的长度是否非0 -z str --str的长度是否为0
case命令:
case variable in
pattern1 | pattern2) commands1;;
pattern3) commands2;;
*) default commands;;
esac
for命令:
for var in list
do
commands
done
c语言风格的for语句:
for (( variable assignment ; condition ; iteration process ))
如 for( (a=1; a<10; a++))
while语句
while test command
do
commands
done
例子:
#!/bin/bash
var1=10
while [ $var1 -gt 0 ]
do
echo $var1
var1=$[ var1 - 1 ]
done
until命令:
until命令要求你指定一个通常返回非零退 出状态码的测试命令。只有测试命令的退出状态码不为0,
bash shell才会执行循环中列出的命令。 一旦测试命令返回了退出状态码0,循环就结束了。
until test command
do
commands
done
例子:
#!/bin/bash
var=100
until [ $var -eq 0 ]
do
echo $var
var=$[ $var - 10 ]
done
linux-shell中同样可以使用break和continue来控制循环
break用来跳出当前循环,继续往下执行。
continue用来跳出循环,继续下一次循环。