shell练级笔记三—循环的使用
定义
循环可以不断地执行某个程序段落,直到达到设定的条件为止。
不定循环
# 当conditin的条件成立时就进行循环
while [condition]
do
......
done
#当conditin的条件成立时就终止循环
util [condition]
do
......
done
实验
while [ "$yn" != "yes" -a "$yn" != "YES" ]
do
read -p "please input yes/YES to stop this program." yn
done
echo -e "\n OK! you input the correct answer."
until [ "$yn" == "yes" -o "$yn" == "YES" ]
do
read -p "please input yes/YES to stop this program." yn
done
echo -e "\n OK! you input the correct answer."
固定循环
#
for var in con1,con2,con3......
do
......
done
#以上面的程序为例
#第一次循环的内容为 con1
#第二次循环的内容为 con2
#第三次循环的内容为 con3
实验
管线命令 cut捉出单纯的账号名称后,以 id 及 finger分别检查使用者的标识符与特殊参数呢
#!/bin/bash
#Program
# Use id, finger command to check system account's information.
#History
#2020-02-12 chuantao first shell scrpit
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:~/bin
export PATH
users=$(cut -d ':' -f1 /etc/passwd)
for username in $users
do
id $username
finger $username
done
for数值处理
for ((初始值;限制值;执行步阶))
do
......程序段
done
实验
#!/bin/bash
#Program
# Try to calculate 1+2+3+....+${your_input}
#History
#2020-02-12 chuantao first shell scrpit
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:~/bin
export PATH
read -p "Please input a number, I will count for 1+2+...+your_input:" nu
s=0
for((i=1;i<="$nu";i++))
do
s=$(($s+$i))
done
echo "the result of '1+2+3+...+$nu is ===> $s"