我的新浪微博:http://weibo.com/u/1602714773
CSDN博客:http://blog.csdn.net/hunterno4
Linux Shell笔记之结构循环
上一篇 /
下一篇 2013-11-05 21:54:15
/ 个人分类:Linux
一、条件语句1.if—then#!/bin/bashif date 如果命令运行成功(退出码为0),则then部分的命令被执行then echo "good"fi2.if—then—else#!/bin/bashif hunterthen echo "good"else echo "bad" if语句中退出码非0,则执行else部分语句fi3.elif#!/bin/bashif hunterthen echo "command not found"elif date 多重If判断then echo "date"fi4.test命令 与其它编程语言思维一样的方式#!/bin/bashif test 1 -eq 2 test命令列出条件成立则退出并返回状态码0,命令等同if [ 1 -eq 2]then echo "right"else echo "wrong"fi5.条件比较1)数据比较n1 -eq n2 相等n1 -ge n2 大于或等于n1 -gt n2 大于n1 -le n2 小于等于n1 -lt n2 小于n1 -ne n2 不等于2)字符串比较str1 = str2str1 != str2str1 < str2str1 > str2-n str1 检查str1的长度是否非0-z str1 检查str1的长度是否为0#!/bin/bashstr1=goodstr2=wrongif [ $str1 \> $str2 ] 大于号需要转义,否则脚本会当重定向符号then echo "$str1 is greater than $str2"else echo "$str1 is less than $str2"fi#!/bin/bashstr=if [ -z "$str" ] 判断字符串是否为空,空的或未初始化的变量对Shell脚本很致命then echo "empty"else echo "not empty"fi3)文件比较-d file 检查文件是否存在且为目录-e file 检查文件是否存在-f file 检查文件是否存在且为文件-r file 检查文件是否存在且可读-s file 检查文件是否存在且非空-w file 检查文件是否存在且可写-x file 检查文件是否存在且可执行-O file 检查文件是否存在且属当前用户-G file 检查文件是否存在且默认组与当前用户相同file1 -nt file2 检查file1是否新于file2file1 -ot file2 检查file1是否旧于file24)复合条件&&与、||或#!/bin/bashif [ -e str ] && [ -f zero ]then echo "file all exist"fi5)双圆括号#!/bin/bashstr1=goodstr2=wrongif (( $str1 > $str2 )) 双圆括号中表达式里的大于号不用转义then echo "$str1 is greater than $str2"else echo "$str1 is less than $str2"fi6)双方括号#!/bin/bashif [[ $USER == r* ]] 支持通配符模式then echo "welcome root user"else echo "sorry"fi7)case分支#!/bin/bashcase $USER inroot|hunterno4) echo "welcome root user";; 尾部两个分号mysql) echo "welcome to database";;surfftp) echo "nice to meet you";;*) 都不匹配时的default语句 echo "i don't know you";;esac二、循环语句1.for命令1)for循环#!/bin/bashfor command in `ls /bin` for循环默认每个值以空格来分割do echo "command in /bin is $command"done#!/bin/bashfor file in /usr/local/program/package/*do if [ -d "$file" ] 文件用引号圈起,以避免文件含空格等情况 then echo "$file is a directory" elif [ -f "$file" ] then echo "$file is a file" fidone2)字段分隔符#!/bin/bashIFS.OLD=$IFS IFS=$'\n' 修改IFS分隔符为换行符,也可同时赋值为:;"等等for str in `cat /home/hunterno4/passwd`do echo "str in passwd is $str"doneIFS=$IFS.OLD 恢复IFS分隔符默认值3)C语言风格的for循环#!/bin/bashfor ((i = 0;i<5 ;i++)) 此时变量与值间可以有空格,变量不用加$号do echo "current number is $i"done2.while命令#!/bin/bashi=5while [ $i -gt 0 ]do echo $i i=$[ $i-1 ]done3.嵌套循环#!/bin/bashIFS.OLD=$IFSIFS=$'\n'for row in `cat /etc/passwd`do echo "passwd row in $row ———" IFS=$':' for words in $row do echo " $words" donedoneIFS=$IFS.OLD4.循环控制1)break#!/bin/bashi=5while [ $i -gt 0 ]do echo $i i=$[ $i-1 ] if [ $i -eq 3 ] then break 自动终止最里面的循环,break n,终止n层循环 fidone2)continue#!/bin/bashi=10while [ $i -gt 0 ]do i=$[ $i-1 ] if [ $i -gt 3 ] && [ $i -lt 6 ] then continue continue n则指定继续执行哪级循环 fi echo "$i"done > output.txt 将循环过程中的结果重定向输出到文件
收藏
举报
TAG:
for
if
Linux
linux
shell
Shell
while