现在的位置: 首页 > 综合 > 正文

shell基础知识学习三

2013年08月22日 ⁄ 综合 ⁄ 共 1275字 ⁄ 字号 评论关闭

继续流程控制

这篇是case,它能够吧变量的内容和多个对比字符进行匹配,匹配成功则执行这部分代码。它匹配只能是字符串。

书写结构如下:

case  匹配符 in 
对比符号)语句;;
对比符号)语句;;
对比符号)语句;;
esac

注意:执行语句的后面必须是双分号;;。
举个例子:

当前目录下有文件a.txt,

file  a.txt
#执行结果
a.txt: ASCII text

就用它的执行结果进行匹配,程序如下

#!/bin/sh
fileType=`file "$1"` # aa: ASCII text
echo ${fileType}
case ${fileType} in
aa*) echo 'this is file name';;
ASCII) echo 'this is file code';;
text) echo 'this is type';;
*) echo 'this is end'
esac
#执行结果
this is file name

 

上面程序需要注意的地方:fileType=`file "$1"`,最外面的不是单引号,是反引号(也有人说叫重音符,随便什么自己知道就可以了)在tab键的上面。

在ruby中调用shell脚本使用重音符,例如:`sh  test.sh`

 

shell中循环有:for、while

1、while

 基本结构:

while [ 条件表达式 ]
do
  ......
done
 
巨汗啊啊!写了半天死机了,csdn没有自动保存吗。重新写吧
写个例子:
echo 'put a:'
read a
while [ ${a} -lt 100 ]
do
  echo ${a}
  a=` expr ${a} + 1 `
done

程序:输入数字,是否小于100,小于则输出且+1

 执行结果:输入96,输出:96 97 98 99

下面是个很有意思的小程序,输出结果如下:

00
101
2102
32103
432104
5432105
65432106
765432107
8765432108
98765432109

程序实现方法有很多,以下仅供参考。

i=0
while [ ${i} -lt 10 ]
do
  y=${i}
  while [ ${y} -ge 0 ]
  do
   echo -n ${y}
   y=` expr ${y} - 1 `
  done
  echo ${i}
  i=` expr ${i} + 1 `
done

2、for

基本结构:

for  没有$的变量 in  变量
do
   ...........
done

字符串的for循环,就是对字符串按照空格拆分。示例如下:

for i in "a s d f g h"
do
 echo ${i}
done
#输入结果:a s d f g h

数字循环。获取10以内能被三整除的整数,示例如下:

for i in $(seq 10)
do
if((i%3==0))
then
echo $i
fi
done

#执行结果:
3
6
9

配合命令的执行。展示当前目录下的文件,示例:

all=` sudo ls `
for i in ${all}
do
 echo ${i}
done

#执行结果:
aa
cycle.sh
operFile.sh
out.txt
process.sh
rename.sh
stderr.txt
stdout.txt
test.sh
trackCodeCheck.rb

此外shell中的循环还有until、select,具体应用可以查看相应资料。

抱歉!评论已关闭.