学习内容
不定循环 while do done、until do done
固定循环 for…do…done
shell脚本的跟踪和调试
学习过程:
12.5 循环(loop)
12.5.1 while do done、until do done(不定循环)
不定循环语法:
#当condition条件成立时,进行循环,直到条件不成立
while [ condition ]
do
somethings
done
#condition条件成立时,终止循环,否则持续进行循环
util [ condition ]
do
somethings
done
例程:1~100求和
#!/bin/bash
sum=0
i=0
while [ "${i}" != "100" ]
do
i=$(($i+1))
sum=$(($sum+$i))
done
echo $sum
12.5.2 for…do…done(固定循环)
for语法:
for var in con1 con2 con3 ...
do
somethings
done
例程1:id检查所有用户的标识符和特殊符号
#!/bin/bash
users=$(cut -d ':' -f1 /etc/passwd)
for username in ${users}
do
id ${username}
done
表示连续的数字或字母:
#方法1:使用sequence
echo $(seq 1 10)
#方法2:使用bash内置机制
echo ${a..g)
例程2:查看路径下文件名的权限
read -p "input" dir
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} exectable"
echo "the file ${dir}/${filename}'s permission is ${perm}"
done
12.5.3 for…do…done的数值处理
语法
for (( 初始值; 限制值; 赋值运算 ))
**注意空格**
12.5.4 搭配随机数与数组的实验
12.6 shell脚本的跟踪和调试
sh [-nvx] scripts.sh
-n : 不执行脚本,进查询语法问题
-v : 执行脚本前,先将内容输出到屏幕
-x : 将使用到的脚本内容显示到屏幕上