目录
1 if结构化命令
if command
then commands
fi(bash shell 会用fi语句在if then之后表示该语句结束)
elif命令检查系统是否有该用户,若有就输出该用户目录下的文件
#!/bin/bash
#testing the else statement
echo "*****************************"
echo "test else satemenr"
user=lys
if grep $user /etc/passwd
then
echo "$user was found in the system:"
ls -a /home/$user/.b*
else
echo "the user $user does not exist on this system."
echo
fi
echo "***********************"
#if (if)
echo "test the nested if statement"
if grep $user /etc/passwd
then
echo "the user $user exists on this system:"
ls -a /home/$user/.b*
else
echo "the user $user does not exist on this system."
if ls -d /home/$user/
then
echo "However. $user has a directorty."
fi
fi
echo
2 for结构化命令
创建循环进行遍历
for命令基本格式:
for var in list
do commands
done
IFS=:
for s in $HOME
do
echo "$s:"
for file in $s/*
do
if [ -x $file ]
then
echo " $file"
echo"文件可执行 "
fi
done
done
运行结果如下:
3 while结构化命令
当语句符合条件程序继续进行如果状态码不是0的话则终止程序。
while命令基本结构:
while test command
do other commands
done
代码展示
#!/bin/bash
#while command test
echo "***** while command test*****"
var1=5
while [ $var1 -gt 0 ]
do
echo $var1
var1=$[ $var1 - 1 ]
done
echo
#using mulriple test command
echo "*****using mutiple test command*****"
var1=5
while echo $var1
[ $var1 -ge 0 ]
do
echo "This is inside the loop"
var1=$[ $var1 - 1 ]
done
echo
运行结果如下:
4 until迭代语句
与while命令不同until语句需要指定一个条件当满足这个条件后退出
until命令基本结构:
until test command
do other commands
done
嵌套循环
打印九九乘法表
y轴循环九次,且打印九行空行
x轴打印与y轴的乘积
#!/bin/bash
y=1
until [ $y -gt 9 ]
do
x=1
until [ $x -gt $y ]
do
echo -ne "$x*$y=$[ $x*$y ]\t"
let x++
done
echo
echo
let y++
done
结果展示: