导语:
bash脚本的循环语句:将一段代码重复执行多次;
脚本代码循环执行需要具备2个条件;
进入条件:条件满足时才进入循环;
退出条件:每个循环都应该有退出条件,以有机会退出循环;
bash脚本的3种循环语句:for循环、while循环、until循环;
for循环
1、 for循环的2种格式
遍历列表;
控制变量;
2、 for循环的遍历列表格式
2.1 语法格式:
for VARAIBLE in LIST; do
循环体
done
进入循环的条件:只要列表里面有元素即可进入循环;
退出循环的条件:列表中的元素遍历完成;
2.2 LIST列表的生成方式
1>. 直接输出方式
2>. 整数列表方式
a. {first…last}
b. seq [OPTION]… LAST
seq [OPTION]… FIRST LAST
seq [OPTION]… FIRST INCREMENT LAST
3>. 返回列表的命令:ls, cat…
4>. glob模式匹配
5>. 变量引用(特殊变量): $* , $@ ,…
for循环举例1(列表直接输出):
————————–
#!/bin/bash for username in user01 user02 user03; do if id $username &> /dev/null; then echo "$username is exists." else useradd $username && echo "add user $username finished." fi done
for循环举例2(整数列表方式):
计算100以内的正整数之和;
———————————-
#!/bin/bash declare -i sum=0 for i in {1..100}; do echo "\$sum is $sum,\$i is $i" sum=$[$sum+$i] done echo $sum
for循环举例3(glob模式匹配):
判断’/var/log’目录下的每个文件的内容类型;
——————————————————
#!/bin/bash for filename in /var/log/*; do if [ -f $filename ]; then echo "common file type." elif [ -d $filename ]; then echo "directory file type." elif [ -b $filename ]; then echo "block special file type." elif [ -c $filename ]; then echo "character special file type." elif [ -L $filename ]; then echo "symbolic file type." elif [ -S $filename ]; then echo "socket file type." else echo "unknow file type." fi done
for循环举例4:
分别求100以内所有偶数之和,以及所有奇数之和;
————————————————————
#!/bin/bash declare -i even_num_sum=0 declare -i odd_num_sum=0 for i in {1..100}; do res=`expr $i % 2` if [ $res -eq 0 ]; then echo "$i is even number." even_num_sum=$[$even_num_sum+$i] else echo "$i is odd number." odd_num_sum=$[$odd_num_sum+$i] fi done echo "\$even_num_sum is $even_num_sum." echo "\$odd_num_sum is $odd_num_sum."
for循环举例5:
计算当前系统上所有用户的ID之和;
—————————————
#!/bin/bash user_name=$(cut -d: -f1 /etc/passwd) declare -i user_id_sum=0 for username in $user_name;do user_id=`id -u $username` user_id_sum=$[$user_id_sum+$user_id] done echo "$user_id_sum"
for循环举例6:
通过脚本参数传递一个目录给脚本,计算此目录下所有文本文件的行数之和;并说明此类文件的总数;
————————————————————————————————————————
#!/bin/bash if [ $# -lt 1 -o $# -ge 2 ]; then echo "Just need one arg , this arg is a directory." exit 11 fi if ! [ -d $1 ]; then echo "It is not a directory." exit 22 fi #if [ -z $1 ]; then # echo "It is a empty directory." # exit 33 #fi list_type_file=`find $1 -type f` count_type_file=`find $1 -type f | wc -l` declare -i line_num_sum=0 for filename in $list_type_file; do line_num=`cat $filename | wc -l` line_num_sum=$[$line_num_sum+$line_num] done echo "\$line_num_sum is $line_num_sum." echo "The type of files are $count_type_file." if [ $count_type_file -eq 0 ]; then echo "$1 is a empty directory." fi