shell中的循环及条件判断


 

for循环的一般格式如下:

复制代码
 1 #!/bin/sh
 2 
 3 for 变量 in 列表
 4 do
 5     command 1
 6     command 2
 7     command 1
 8  ......... 9  command n 10 done
复制代码

列表是一组值(数字、字符串等)组成的序列,每个值通过空格分隔。每循环一次,就将列表中的下一个值赋给变量。
列表也可以是一个文件:
in 列表是可选的,如果不用它,for 循环使用命令行的位置参数。

复制代码
1 #!/bin/sh
2 
3 for line in 1 2 3 4 5 6 7
4 do
5     echo "line is $line"
6 done
复制代码

结果:

[root@localhost 1st]# sh test.sh
line is 1 line is 2 line is 3 line is 4 line is 5 line is 6 line is 7

 

下面用for循环读一个文件:

查看文件内容

复制代码
1 [root@localhost 1st]# cat test.txt 
2 hello 3 wolrd 4 hello 5 shell 6 [root@localhost 1st]#
复制代码

code:

复制代码
1 #!/bin/sh
2 
3 FILE=./test.txt
4 
5 for line in $(<$FILE) 6 do 7 echo "line is: $line" 8 done
复制代码

Results:

复制代码
1 [root@localhost 1st]# sh xx.sh  
2 line is: hello
3 line is: wolrd 4 line is: hello 5 line is: shell 6 [root@localhost 1st]# 
复制代码

while循环的一般格式如下:

复制代码
1 while command
2 do
3 
4  statement 5 6 done
复制代码

code:

复制代码
 1 #!/bin/sh
 2 
 3 i=0
 4 sum=0
 5 while [ $i -le 100 ]
 6 do 
 7    sum=$(($sum + $i)) 8 i=$(($i + 1)) 9 done 10 echo "sum is $sum"
复制代码
rusults:
1 [root@localhost 1st]# sh xx.sh 
2 sum is 5050
3 [root@localhost 1st]#

if语句的一般格式如下:

复制代码
1 if ....; then
2 ....
3 elif ....; then
4 .... 5 else 6 .... 7 fi
复制代码

if 条件语句:

文件表达式:

复制代码
 1 [ -f "somefile" ] :  判断是否是一个文件 
 2 [ -x "/bin/ls" ] :    判断/bin/ls是否存在并有可执行权限 3 [ -n "$var" ] :    判断$var变量是否有值 4 [ "$a" = "$b" ] :  判断$a和$b是否相等 5 -r file       用户可读为真 6  -w file       用户可写为真 7  -x file       用户可执行为真 8  -f file       文件为正规文件为真 9  -d file       文件为目录为真 10  -c file       文件为字符特殊文件为真 11  -b file       文件为块特殊文件为真 12  -s file       文件大小非0时为真 13  -t file       当文件描述符(默认为1)指定的设备为终端时为真
复制代码
更短的if语句
# 一行
# Note: 当第一段是正确时执行第三段
# Note: 此处利用了逻辑运算符的短路规则
[[ $var == hello ]] && echo hi || echo bye
[[ $var == hello ]] && { echo hi; echo there; } || echo bye

字符串表达式:

[string string_operator string]

这里string_operator可为如下几种:

1 =     两个字符串相等。
2 != 两个字符串不等。 3 -z 空串。 4 -n 非空串

eg:

复制代码
1  #!/bin/sh
2  
3  NUMS="hello"
4  [ $NUMS = "hello" ]
5  
6  echo $?
复制代码

results:

1 [root@localhost 1st]# sh xx.sh  
2 0

 整数表达式:

复制代码
1 -eq   数值相等。
2 -ne 数值不相等。 3 -gt 第一个数大于第二个数。 4 -lt 第一个数小于第二个数。 5 -le 第一个数小于等于第二个数。 6 -ge 第一个数大于等于第二个数。
复制代码

 Eg:

复制代码
1 #!/bin/sh
2 
3 NUMS=130
4 if [ $NUMS -eq "130" ]; then
5 
6     echo "equal"
7 else
8     echo "not equal"
9 fi
复制代码

results:

1 [root@localhost 1st]# sh xx.sh 
2 equal

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM