for語句的使用

2021-08-06 06:17:56 字數 2492 閱讀 1483

在程式語言中少不了使用邏輯結構去進行操作繁雜的操作,這樣解決了繁瑣的步驟,容易讓別人讀懂。

在linux中有常用的三種迴圈迴圈:for,while,until

基本規則:

迴圈體:要執行的**;可能要執行n遍;

進入條件;

退出條件;

1、for迴圈的格式

for迴圈:

for 變數名 in 列表;do

迴圈體done

執行機制:依次將列表中的元素賦值給「變數名」;每一次賦值都執行一次迴圈體;直到列表中的元素耗盡,迴圈結束。

示例:新增10個使用者,user1-user10,密碼同使用者名稱

#!/bin/bash

#if [ !$uid -eq 0 ];then

echo "only admin can create username."

exit 1

else

for i in ;do

if id user$1 &>/dev/null;do

echo "the username has done."

else

useradd user$i

echo "user$i" |passwd --stdin user$i &>/dev/null

echo "add user$1 finished."

done

fi

2、在for迴圈中列表的生成方式

(1)直接給出字串列表

(2)整數列表

(a)(b)$(seq[start[step]end])

(c)返回列表的命令 $(command)

(d)glob

(e)變數引用

$@ $*

示例:判讀某路徑下所有檔案型別

#!/bin/bash

#for file in $(ls /var);do

if [ -f /var/$file ];then

echo "common file"

elif [ -d /var/$file ];then

echo "directory"

elif [ -l /var/$file ];then

echo "symbloic file"

else

echo "other file"

fi

在for迴圈中先後次序至關重要。 例如上面的示例先判斷目錄和先判斷鏈結檔案顯示的結果時截然不同的。

示例:判斷狀態

#!/bin/bash

#declare estab=0

declare listen=0

declare other=0

for state in $(netstat -tan |grep 'tcp'|awk '');do

if [ "$stat"=="establehed" ];then

let estab++

elif [ "$stat"=="listen" ];then

let listen++

else

let other++

fidone

echo "established:$estab"

echo "listen:$listen"

echo "other:$other"

練習1:/etc/rc.d/rc3.d目錄下分別有多個以k開頭和以s開頭的檔案:

分別讀取每乙個檔案,而後輸出;k開頭 ,「輸出檔名 stop」 ;s開頭的輸出「檔名 start」

#

for filename in $(ls /etc/rc.d/rc3.d);do

if [ "$filename"=~"k*" ];then

echo

"$filename stop"

elif [ "$filename"=~"s*" ];then

echo

"$filename start"

else

echo

"oter type"

fidone

#

read -p "enter enternet number,for example 172.16.0: " ipnumber

for num in ;do

if ping -c 1 -w 1

$ipnumber.$num >/dev/null ;then

echo

"the state is active"

else

echo

"the state isn't active"

fidone

with語句的使用

with語句的解釋 指定臨時命名的結果集,這些結果集稱為公用表表示式 cte 該表示式源自簡單查詢,並且在 select insert update 或 delete 語句的執行範圍內定義。該子句也可用在 create view 語句中,作為該語句的 select 定義語句的一部分。公用表表示式可以...

if語句的使用

學習if語句主要是用來判斷程式裡面的條件是否成立。if語句的語法格式 if 要判斷的條件 條件滿足會執行if語句裡面的 age 19 print if語句要開始判斷啦.判斷條件 if age 18 當if條件滿足,會執行if語句裡面的 print 哥已成年,可以進入網咖玩耍 print if語句判斷...

with語句的使用

with語句的解釋 指定臨時命名的結果集,這些結果集稱為公用表表示式 cte 該表示式源自簡單查詢,並且在 select insert update 或 delete 語句的執行範圍內定義。該子句也可用在 create view 語句中,作為該語句的 select 定義語句的一部分。公用表表示式可以...