shell基础知识学习三

来源:互联网 发布:大数据风控查询 编辑:程序博客网 时间:2024/04/28 21:43

继续流程控制

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

书写结构如下:

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

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

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

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


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

#!/bin/shfileType=`file "$1"` # aa: ASCII textecho ${fileType}case ${fileType} inaa*) 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 awhile [ ${a} -lt 100 ]do  echo ${a}  a=` expr ${a} + 1 `done

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

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

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

00101210232103432104543210565432106765432107876543210898765432109


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

i=0while [ ${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)doif((i%3==0))thenecho $ifidone#执行结果:369

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

all=` sudo ls `for i in ${all}do echo ${i}done#执行结果:aacycle.shoperFile.shout.txtprocess.shrename.shstderr.txtstdout.txttest.shtrackCodeCheck.rb


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

原创粉丝点击