until循环控制结构
本节例子来源:http://blog.chinaunix.net/uid-25880122-id-2901409.html 语法格式:
while expression do command command done适用于循环次数已知或固定时
root@sparkslave02:~/ShellLearning/Chapter13# vim whileLoop.sh .#!/bin/bash i=1 while(($i<5)) do echo $i let i++ done root@sparkslave02:~/ShellLearning/Chapter13# chmod a+x whileLoop.sh root@sparkslave02:~/ShellLearning/Chapter13# ./whileLoop.sh 1 2 3 4## 2. if条件判断## 参考:http://blog.chinaunix.net/uid-20735106-id-3434959.html shell 脚本中的if条件判断功能十分强大,但使用也异常复杂,其语法格式:
if 条件 then Command else Command #if条件判断的结束,用反拼表示 fi最常用的判断为:判断字符串、判断数字、判断文件及逻辑判断等
使用示例:
root@sparkslave02:~/ShellLearning/Chapter13# vim if02.sh i=2 j=3 if [ $i -lt $j ] then echo "i is less than j" fi if [ $j -gt $i ] then echo "j is great than i" fi root@sparkslave02:~/ShellLearning/Chapter13# chmod a+x if02.sh root@sparkslave02:~/ShellLearning/Chapter13# ./if02.sh i is less than j j is great than i文件判断常用命令如下:
1. -r file --用户可读为真 2. -w file --用户可写为真 3. -x file --用户可执行为真 4. -f file --文件存在且为正规文件为真 5. -d file --如果是存在目录为真 6. -c file --文件存在且为字符设备文件 7. -b file --文件存在且为块设备文件 8. -s file --文件大小为非0为真,可以判断文件是否为空 9. -e file --如果文件存在为真使用示例:
root@sparkslave02:~/ShellLearning/Chapter13# vim if03.sh root@sparkslave02:~/ShellLearning/Chapter13# chmod a+x if03.sh #判断文件是否存在 if [ -f if03.sh ] then echo "if03.sh exists!!" fi #判断目录是否存在 if [ -d ../Chapter13 ] then echo "directory Chapter13 exists!!" fi root@sparkslave02:~/ShellLearning/Chapter13# ./if03.sh if03.sh exists!! directory Chapter13 exists!!逻辑判断主要有下面三个命令
1. -a --与 2. -o --或 3. ! --非使用示例:
root@sparkslave02:~/ShellLearning/Chapter13# vim if04.sh #判断if04.sh文件与目录Chapter13是否同时存在,同时存在则为真 if [ -f if04.sh -a -d ../Chapter13 ] then echo "file if04.sh and directory Chapter13 both exists!!!" fi root@sparkslave02:~/ShellLearning/Chapter13# chmod a+x if04.sh root@sparkslave02:~/ShellLearning/Chapter13# ./if04.sh file if04.sh and directory Chapter13 both exists!!!前面给出的例子都是if [] then fi的形式,这里再给出if [] then else fi的用法
root@sparkslave02:~/ShellLearning/Chapter13# vim if05.sh i=7 if [ $i -lt 6 ] then echo "i is less than 6" else echo "i is great than or equal 6" fi root@sparkslave02:~/ShellLearning/Chapter13# chmod a+x if05.sh root@sparkslave02:~/ShellLearning/Chapter13# ./if05.sh i is great than or equal 6多种判断,看示例代码就能明白:
root@sparkslave02:~/ShellLearning/Chapter13# cp if05.sh if06.sh root@sparkslave02:~/ShellLearning/Chapter13# vim if06.sh i=7 if [ $i -le 6 ] then echo "i is less than 6" elif [ $i -eq 7 ] then echo "i equal 7" else echo "i is great than 7" fi root@sparkslave02:~/ShellLearning/Chapter13# ./if06.sh i equal 7## 3. until循环控制结构##
语法格式:
until condition do command done使用示例:
root@sparkslave02:~/ShellLearning/Chapter13# vim until01.sh i=0 until [ $i -gt 2 ] do let i+=1 echo "i=$i" done root@sparkslave02:~/ShellLearning/Chapter13# chmod a+x until01.sh root@sparkslave02:~/ShellLearning/Chapter13# ./until01.sh i=1 i=2 i=3