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
需要注意的是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: 文件名
$*: 所有位置變量的內容
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
以上就是小編的分享了,希望能夠幫助到大家。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com