shell腳本程式設計之循環控制結構
循環控制之for循環
文法結構1
for Variable in List
do
commands
done
文法結構2
for Variable in List;do
這個List可以為清單、變量、指令 等等
for循環 事先提供一個元素清單,而後,使用變量去周遊此元素清單,每通路一個元素,就執行一次循環體,直到元素通路完畢
1、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
運作結果

2、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
3、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
運作結果
4、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."
5、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,