shell脚本编程之循环控制结构面试
循环控制之for循环shell
语法结构1编程
for Variable in Listbash
doide
commands测试
doneui
语法结构2spa
for Variable in List;do3d
commandsblog
done
这个List能够为列表、变量、命令 等等
for循环 事先提供一个元素列表,然后,使用变量去遍历此元素列表,每访问一个元素,就执行一次循环体,直到元素访问完毕
一、for循环中的List为列表
eg1: 显示/etc/inittab, /etc/rc.d/rc.sysinit, /etc/fstab三个文件各有多少行;
#!/bin/bash for File in /etc/inittab /etc/rc.d/rc.sysinit /etc/fstab;do Row=`wc -l $File | cut -d' ' -f1` echo "$File has: $Row rows" done
运行结果
二、for循环中的List为变量
eg2:显示当前ID大于500的用户的用户名和id;
#!/bin/bash useradd user1 useradd user2 useradd user3 #新建几个用户便于测试结果 Id=`cat /etc/passwd | awk -F: '{print $3}'` for Var in $Id;do if [ $Var -ge 500 ];then User=`grep "$Var\>" /etc/passwd | cut -d: -f1` echo "$User uid is $Var" fi done
运行结果
三、for循环中的List为命令
eg3:显示当前shell为bash的用户的用户名和shell。
显示结果为 Bash user:root,/bin/bash
分析:先经过以bash结尾的shell来肯定用户,而后把这些用户一个一个的输出
#!/bin/bash for Var in `grep "bash\>" /etc/passwd | cut -d: -f7`;do User=`grep "$Var" /etc/passwd |cut -d: -f1` done Shell=`grep "bash\>" /etc/passwd |cut -d: -f7 |uniq` for name in $User;do echo "Bash user:$name,$Shell" done
运行结果
四、for循环中的List为一连串的数字
eg4:分别计算1-100之内偶数(Even number)的和,奇数(Odd number)的和.
分析:当一个数与2取余用算时,为1则表示该数为奇数,反之为偶数。
#!/bin/bash EvenSum=0 OddSum=0 for I in `seq 1 100`;do if [ $[$I%2] -eq 1 ]; then OddSum=$[$OddSum+$I] else EvenSum=$[$EvenSum+$I] fi done echo "EvenSum: $EvenSum." echo "OddSUm: $OddSum."
运行结果
五、C语言格式的for循环
eg5:添加用户从user520添加到user530,且密码与用户名同样。
#!/bin/bash for ((i=520;i<=530;i++));do useradd user$i echo "Add user$i." echo user$i | passwd -stdin user$i &>/dev/null done
运行结果:(能够切换一个用户试试密码是否和用户名同样)
其余循环的格式以下,全部这些循环熟练掌握一种循环便可。
while循环命令的格式
while test command
do
other command
done
until循环的命令格式
until test command
do
other command
done
一个脚本的面试题 ,各位博友能够把您的答案回复在下面(你们一块儿交流)
经过传递一个参数,来显示当前系统上全部默认shell为bash的用户和默认shell为/sbin/nologin的用户,并统计各种shell下的用户总数。
运行如 bash eg.sh bash则显示结果以下
BASH,3users,they are:
root,redhat,gentoo,
运行如 bash eg.sh nologin则显示结果以下
NOLOGIN, 2users, they are:
bin,ftp,