七、bash脚本中的流程控制
条件判断控制
-[]([]中的表达式是否为真) &&(前边的结果是true的时候执行后边的命令) ||(前边的结果是false的时候执行后边的命令)
-if
-case
循环控制
-while
-utile
-for
-break
-continue
#[ abc ]
#echo $?
0(表示true)
#[ ]
#echo $?
1(表示false)
#["$USER" = "byf" ]('$?*'的意义是去掉特殊意义的字符,“ ”双引号只是去掉空格的特殊意义)
#echo $?
1
#[$USER = root ]
#echo $?
#[$USER = root ] && echo hello root
hello root
#[-x /etc/] && echo hello
hello
#man bash中输入/-w即可查找,n查找下一个
#-r(读) -w(写) -x(可执行) -f(普通文件) -d(是否有目录) -L (链接)-b(block的适配文件) -c
#[-b /dev/hda ]&& echo you have a ide device
#[-b /dev/sda ]&& echo you have a scsi device
you have a scsi device
#[-f /usr/sbin/httpd] && echo please install httpt again
please install httpd again
#vi b
#!/bin/bash
read AAA
if [ $AAA = byf ]
then
echo hello byf
elif [ $AAA = root ]
then
echo hello root
else
echo 'get out here'
fi
wq
#./b
#bash -v ./b(看执行到那个命令)
#bash -vx ./b(查看出错命令行,进行调试,可查看每个变量的值)
C和bash调试的差别
C是纯二进制的文件,调试需要相应的开发环境设置断点
bash中是文本的文件,可直接检测到出错的地方
#
#!/bin/bash
read AAA
case $(取出变量的值)AAA in
byf )
echo hello byf
echo nice to meet you
;;(表示结束)
root )
echo hello root
echo i miss you so much
;;
* )
echo get out here
;;
esac
:wq
#bash ./c
byf
-eq = 相同
-ne !=不同
-gt >
-lt <
-ge >=
-le <=
-z 为空
#!/bin/bash
AAA="`pgrep httpd`"
[-z "$AAA"("3186 3188 3189 3190 3191 3192 3193 3194 3195
"去掉变量中的空格)]&& echo httpd 'httpd is not running!' && exit
for i in $AAA
do
kill -9 $i
done
echo httpd is killed
wq
#chmod a+x d
#./d
#./d
#!/bin/bash
for aaa in 111 222 333 /etc/profile.d/*.h
do
echo $aaa (chmod a+ x $aaa批量操作)
done
#chmod a+x e
#./e
111
222
333
/etc/profile.d/colorls.sh /etc/profile.d/glib2.sh /etc/profile.d/gnome-ssh-askpass.sh /etc/profile.d/kde.sh /etc/profile.d/lang.sh /etc/profile.d/less.sh /etc/profile.d/qcd.sh /etc/profile.d/qt.sh /etc/profile.d/udisks-bash-completion.sh /etc/profile.d/vim.sh /etc/profile.d/which2.sh
#seq 1 100
1
2
……
100
#!/bin/bash
for aaa in `seq 1 100`
do
echo $aaa; sleep 1(分号不加回车,不加分号加换行)
(echo -n "$aaa"
sleep 1)
done
#
#!/bin/bash
iii=0
while [ $iii -lt 100 ]
do
i=$[$iiii+1]
echo -n "$iii "
done
#
#!/bin/bash
iii=0
until [$iii -gt 100]
do
iii=$[$iii+1]
echo -n "$iii "
done
unset iii
:wq
#
#!/bin/bash
while
true
do
read AAA
if ["$AAA" = "ddd"]
then
break
fi
done