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,