開心生活站

位置:首頁 > IT科技 > 

shell腳本for循環

IT科技8.13K

shell腳本中的for循環是怎樣的呢?下面就讓我們一起來了解一下吧:

在shell腳本中編寫腳本使用for循環一般是用於判斷輸入的用戶名是否存在,若是不存在的話那麼創建該用戶並設置密碼,否則程序會繼續提示用戶,也就是提示重新輸入新建用戶名稱。

在for命令中的for i in的各種用法介紹如下

for i in “file1” “file2” “file3”

for i in /boot/*

for i in /etc/*.conf

for i in $(seq -w 10) --》等寬的01-10

for i in {1…10}

for i in $( ls )

for I in $(< file)

for i in “$@” --》取所有位置參數,可以簡寫爲for i

shell腳本for循環

需要注意的是bash shell支持C式for循環。

示例代碼如下:

#!/bin/bash

j=$1

for ((i=1; i<=j; i++))

do

touch file$i && echo file $i is ok

done

$@: 所有位置變量的內容

$#: 位置變量的個數

$0: 文件

$*: 所有位置變量的內容

shell腳本for循環 第2張

for循環的一般代碼格式爲:

for 變量名 in 列表

do

    command1

    command2

    ...

    commandN

done

參考範例:

範例一

輸入代碼:

for loop in 1 2 3 4 5

do

    echo "The value is: $loop"

done

輸出結果爲:

The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5

範例二

若是編寫腳本清空所有arp緩存記錄,示例代碼如下:

#!/bin/bash

for i in $(arp | tail -n +2|tr -s ' ' |cut -d' ' -f1)

do 

arp -d $i 

done