Linux shell流程控制实例分析
这篇文章主要介绍“Linux shell流程控制实例分析”,在日常操作中,相信很多人在Linux shell流程控制实例分析问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Linux shell流程控制实例分析”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
if语句结构[if/then/elif/else/fi]
if条件测试语句thenaction[elif条件actionelseaction]fi
shell命令,可以按照分号分割,也可以按照换行符分割。如果想一行写入多个命令,可以通过“’;”分割,如:
[chengmo@centos5~]$a=5;if[[a-gt4]];thenecho'ok';fi;
实例:(test.sh)
#!/bin/shscores=40;if[[$scores-gt90]];thenecho"verygood!";elif[[$scores-gt80]];thenecho"good!";elif[[$scores-gt60]];thenecho"pass!";elseecho"nopass!";fi;
(1)for循环使用方法(for/do/done) 1.for … in 语句——语法结构
for变量inseq字符串#seq字符串只要用空格字符分割,每次for…in读取时候,就会按顺序将读到值,给前面的变量。doactiondone
实例(testfor.sh):
#!/bin/shforiin$(seq10);do#seq10产生123……10空格分隔字符串echo$i;done;
2.for((赋值;条件;运算语句))
for((赋值;条件;运算语句))doactiondone;
实例(testfor2.sh):
#!/bin/shfor((i=1;idoecho$i;done;
(2)while循环使用(while/do/done)
while条件语句doactiondone;
实例1:
#!/bin/shi=10;while[[$i-gt5]];doecho$i;((i--));done;
运行结果:
shtestwhile1.sh109876
实例2:(循环读取文件内容:)
#!/bin/shwhilereadline;doecho$line;done
运行结果:
shtestwhile2.sh#Donotremovethefollowingline,orvariousprograms#thatrequirenetworkfunctionalitywillfail.127.0.0.1centos5localhost.localdomainlocalhost
(3)until循环语句——语法结构
until条件#直到满足条件,就退出。否则执行action.doactiondone
实例(testuntil.sh):
#!/bin/sha=10;until[[$a-lt0]];doecho$a;((a—));done;
结果:
shtestuntil.sh109876543210三、shell选择语句(case、select用法)
(1)case选择语句使用(case/esac)——语法结构
case$arginpattern|sample)#arginpatternorsample;;pattern1)#arginpattern1;;*)#default;;esac
❝
说明:pattern1 是正则表达式,可以用下面字符: * 任意字串 ? 任意字元 [abc] a, b, 或c三字元其中之一 [a-n] 从a到n的任一字元 | 多重选择
实例:
#!/bin/shcase$1instart|begin)echo"startsomething";;stop|end)echo"stopsomething";;*)echo"Ignorant";;esac
运行结果:
testcase.shstartstartsomething
(2)select语句使用方法(产生菜单选择)——语法
select变量nameinseq变量doactiondone
实例:
#!/bin/shselectchin"begin""end""exit"docase$chin"begin")echo"startsomething";;"end")echo"stopsomething";;"exit")echo"exit"break;;;*)echo"Ignorant";;esacdone;
运行结果:
到此,关于“Linux shell流程控制实例分析”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。