Linux入门第五天——shell脚本入门(下)基础语法之循环
2017-12-15 21:08
791 查看
一、循环
1.不定循环有两种形式:
while [ condition ] <==中括号内的状态就是判断式 do <==do 是循环的开始! 程序段落 done <==done 是循环的结束
当 condition 条件成立时,就进行循环,直
到 condition 的条件不成立才停止
until [ condition ] do 程序段落 done
当 condition 条件成立时,就终止循环, 否则就持续
进行循环的程序段。
示例
#!/bin/bash #描述:循环练习1 #作者:jiangbei on 2017/12/15 until [ "${yes}" == "yes" -o "${yes}" == "YES" ] do read -p "input yes/YES:" yes done echo "OK,you input the right word!"
示例:1+2+3+...+10的累加:
#!/bin/bash #简介略 ########## declare i=1 declare sum=0 while [ ${i} -le 10 ] do sum=$((${sum}+${i})) i=$((${i}+1)) done echo "the total is ${sum}"
// 第一次把第8行的sum写成num,纠结了半天变量的写法,囧。更多的数值计算,参考:http://www.mamicode.com/info-detail-1324934.html
注意:同样,x权限添加等此处省略...(中括号的左右空格请注意!)
2.固定循环
与经典的for循环类似,此处不再赘述
列举值循环:
语法:
for var in con1 con2 con3 ... do 程序段 done
1. 第一次循环时, $var 的内容为 con1 ;
2. 第二次循环时, $var 的内容为 con2 ;
3. 第三次循环时, $var 的内容为 con3 ;
示例:
#!/bin/bash #略 for animal in dog cat horse do echo "The current animal is ${animal}" done
数字式循环:
使用seq——seq 为 sequence(连续) 的缩写之意,更多seq相关的用法(可以使用反引号`seq 1000`,或者$( seq 1000 )),
参考:http://linux.51yip.com/search/seq
利用数字式改写累加示例如下:
#!/bin/bash #略 declare -i sum=0 for i in $(seq 100) do sum=$((${sum}+${i})) done echo "the total is ${sum}"
当然,还有另外一种写法:{1..100},这是bash内置的写法,并且支持{a..g}表示a到g及中间的字母!
最后,采用循环+判断的写法如下:
最后,让我们来玩判断式加上循环的功能!我想要让使用者输入某个目录文件名, 然后我找
出某目录内的文件名的权限,该如何是好?呵呵!可以这样做啦~
#!/bin/bash #略 read -p "Please input a directory:" dir if [ "${dir}" == "" -o ! -d "${dir}" ];then echo "The ${dir} is not exist!" exit 1 fi filelist=$(ls ${dir}) for file in ${filelist} do perm="" test -r "${dir}/${file}" && perm="${perm}r" test -w "${dir}/${file}" && perm="${perm}w" test -x "${dir}/${file}" && perm="${perm}x" echo "the file ${dir}/${file} has the perm:${perm}" done
输入/tmp就可以测试啦!
数值处理的循环:——熟悉的格式
for (( 初始值; 限制值; 执行步阶 )) do 程序段 done
继续改写累加的示例:
#!/bin/bash #略 declare -i sum=0 for (( i=1; i<=100; i++)) do sum=$((${sum}+${i})) done echo "the total is ${sum}"
再举一个数组的例子(数据类型介绍参考基本概念随笔)
#!/bin/bash #略 #定义数组 list[1]="糖醋排骨" list[2]="麻婆豆腐" list[3]="宫保鸡丁" size=3 check=$((${RANDOM} * ${size} / 32767 + 1)) echo "your choice is ${list[${check}]}"
// shell有一个环境变量RANDOM,范围是0--32767
相关文章推荐
- Linux入门第五天——shell脚本入门(中)基础语法之判断与条件
- Linux入门第五天——shell脚本入门(下)基础语法之调试debug
- Linux bash shell脚本语法入门
- Linux bash shell脚本语法入门
- Linux简单入门(十二)shell脚本之前的基础知识
- Linux bash shell脚本语法入门(转)
- 嵌入式成长轨迹2【嵌入式环境及基础】【嵌入式Linux软件开发入门】【Shell脚本基础】
- 【Linux-shell】shell脚本基础语法练习
- Linux入门之Shell脚本基础
- Linux bash shell脚本语法入门
- 8.17_Linux之bash shell脚本编程入门篇(三)之循环以及函数function的使用
- (转)Linux bash shell脚本语法入门
- 【Linux】中shell脚本语法篇之条件语句和循环语句
- linux 基础学习之五:shell脚本学习(2)——基本语法
- Linux入门第五天——shell脚本入门(上)基本概念
- linux之基础shell脚本编程2 if语句循环判断
- linux之基础shell脚本编程3 函数数组
- shell脚本编程入门基础(附:自动备份与解包文件脚本)
- shell脚本语法基础汇总
- Linux大数据开发基础:第十一节:Shell编程入门(三)