shell腳本編程之循環控制結構

                          shell腳本編程之循環控制結構

循環控制之for循環

     語法結構1

         for  Variable  in List

         do

             commands

         done

     語法結構2

         for  Variable  in List;do

             commands

         done

這個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,













發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章