最近在看《鸟哥的LINUX私房菜 基础学习篇》,目前看到了shell脚本这一章,打算在这里简单记录一下这一整章的学习过程和相关的知识点。
参考资料:《鸟哥的LINUX私房菜 基础学习篇》第四版 第十二章
实验环境: Ubuntu18.04
在上一节中,我们学习了如何在shell脚本中使用条件判断,根据判断的结果分别执行不同的程序段。本节,我们将学习如何在shell脚本中利用循环。
循环也是编程中很重要的内容,通过循环可以让程序自动的、多次执行某一程序段。在shell脚本中主要使用的有三种循环,下面一一进行介绍。
1. 不定循环
最常见的不定循环有两种:while do done和until do done。
#while do done 当条件成立时,就进行循环,直到条件不成立时停止
while [ condition ]
do
程序段落
done
#until do done 当条件成立时,终止循环,否则进行循环
until [ condition ]
do
程序段落
done
-
简单的示例
下面分别用while和until编写了同一个功能的小脚本,来对比它们的不同
#文件名:yes_to_stop.sh
#!/bin/bash
# Program:
# Repeat question until user input correct answer.
# History:
# 2019/2/25 LaiFeng
while [ "$yn" != "yes" -a "$yn" != "YES" ] #当用户输入不是'yes'且'YES'时,执行程序段
do
read -p "Please input yes/YES to stop this program:" yn
done
echo "OK, you input the correct answer."
#文件名:yes_to_stop-2.sh
#!/bin/bash
# Program:
# Repeat question until user input correct answer.
# History:
# 2019/2/25 LaiFeng
until [ "$yn" == "yes" -o "$yn" == "YES" ] #当用户输入是'yes'或者'YES'时,停止
do
read -p "Please input yes/YES to stop this program:" yn
done
echo "OK, you input the correct answer."
2.固定循环 for...do...done
for...do...done的语法:
for var in con1 con2 con3
do
程序段
done
从它语法中可以看出,固定循环其实就是将已知的几个值(con1 con2 con3)分别代入(var),执行程序段。
- 简单的示例
#文件名:show_animal.sh
#!/bin/bash
# Program:
# Using for...loop to print 3 animals
# History:
# 2019/2/25 LaiFeng
for animal in dog cat elephant
do
echo "There are ${animal}s..."
done
再看一个更有趣的示例。在这个示例中,让用户输入某个目录名,然后程序列出该目录下所有文件的权限。
#文件名:dir_perm.sh
#!/bin/bash
# Program:
# User input dir name, I will find the permission of files.
# History:
# 2019/2/25 LaiFeng
read -p "Please input a directory:" dir
#判断目录是否存在
if [ "$dir" == "" -o ! -d "$dir" ]; then
echo "The $dir is NOT exist in your system."
exit 1
fi
#列出目录下所有文件名
filelist=$(ls $dir)
for filename in ${filelist} #遍历所有文件名
do
perm=""
test -r "${dir}/${filename}" && perm="$perm readable"
test -w "${dir}/${filename}" && perm="$perm writable"
test -x "${dir}/${filename}" && perm="$perm executable"
echo "Thie file ${dir}/${filename}'s permission is ${perm}"
done
3. for...do...done 的数值处理
for...do...done还有另一种用法。这种用法与其他编程语言中的用法基本一致。它的语法如下:
for ((初始值;终止条件;赋值运算)) #注意,需要两个括号
do
程序段
done
- 简单的示例
#文件名:cal_1_n.sh
#!/bin/bash
# Program:
# Use loop to calculate "1+2+...+n"
# History:
# 2019/2/25 LaiFeng
read -p "Please input a number, I will count for 1+2+...+n: " num
s=0
for ((i=1;i<=$num;i=i+1))
do
s=$(($s+$i)) #shell脚本数值计算:$((计算式))
done
echo "The result of '1+2+3...+$num' is ==> $s"
以上就是关于shell脚本中循环的简单介绍。想要了解更多关于shell脚本的知识?欢迎参考Linux shell脚本 :)