温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Linux shell流程控制实例分析

发布时间:2022-02-17 15:54:09 来源:亿速云 阅读:114 作者:iii 栏目:开发技术

这篇文章主要介绍“Linux shell流程控制实例分析”,在日常操作中,相信很多人在Linux shell流程控制实例分析问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Linux shell流程控制实例分析”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

Linux shell流程控制实例分析

一、shell条件语句(if用法)

if语句结构[if/then/elif/else/fi]

if 条件测试语句thenaction
[elif 条件
actionelseaction
]fi


shell命令,可以按照分号分割,也可以按照换行符分割。如果想一行写入多个命令,可以通过“’;”分割,如:

[chengmo@centos5 ~]$ a=5;if [[ a -gt 4 ]] ;then echo 'ok';fi;

实例:(test.sh)

#!/bin/shscores=40;if [[ $scores -gt 90 ]]; thenecho "very good!";elif [[ $scores -gt 80 ]]; thenecho "good!";elif [[ $scores -gt 60 ]]; thenecho "pass!";elseecho "no pass!";fi;
Linux shell流程控制实例分析

二、循环语句(for,while,until用法):

(1)for循环使用方法(for/do/done) 1.for … in 语句——语法结构

for 变量 in seq字符串       # seq字符串 只要用空格字符分割,每次for…in读取时候,就                                                              会按顺序将读到值,给前面的变量。doactiondone

实例(testfor.sh):

#!/bin/shfor i in $(seq 10); do     #seq 10 产生 1 2 3 …… 10空格分隔字符串echo $i;done;
Linux shell流程控制实例分析

2.for((赋值;条件;运算语句))

for((赋值;条件;运算语句))doactiondone;

实例(testfor2.sh):

#!/bin/shfor((i=1;idoecho $i;done;
Linux shell流程控制实例分析

(2)while循环使用(while/do/done)

while 条件语句doactiondone;

实例1:

#!/bin/shi=10;while [[ $i -gt 5 ]];doecho $i;
((i--));done;

运行结果:

sh testwhile1.sh
10
9
8
7
6

实例2:(循环读取文件内容:)

#!/bin/shwhile read line;doecho $line;done

运行结果:

sh testwhile2.sh# Do not remove the following line, or various programs# that require network functionality will fail.127.0.0.1 centos5 localhost.localdomain localhost

(3)until循环语句——语法结构

until 条件              #直到满足条件,就退出。否则执行action.doactiondone

实例(testuntil.sh):

#!/bin/sha=10;
until [[ $a -lt 0 ]];doecho $a;
((a—));done;

结果:

sh testuntil.sh
10
9
8
7
6
5
4
3
2
1
0

三、shell选择语句(case、select用法)

(1)case选择语句使用(case/esac)——语法结构

case $arg inpattern | sample) # arg in pattern or sample;;
pattern1) # arg in pattern1;;
*) #default;;esac

说明:pattern1 是正则表达式,可以用下面字符: * 任意字串 ? 任意字元 [abc] a, b, 或c三字元其中之一 [a-n] 从a到n的任一字元 | 多重选择

实例:

#!/bin/shcase $1 instart | begin)echo "start something";;
stop | end)echo "stop something";;
*)echo "Ignorant";;esac

运行结果:

testcase.sh start
start something

(2)select语句使用方法(产生菜单选择)——语法

select 变量name in seq变量doactiondone

实例:

#!/bin/shselect ch in "begin" "end" "exit"docase $ch in"begin")echo "start something";;"end")echo "stop something";;"exit")echo "exit"break;
;;
*)echo "Ignorant";;esacdone;

运行结果:

  Linux shell流程控制实例分析

到此,关于“Linux shell流程控制实例分析”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI