shell腳本中的for循環(huán)是怎樣的呢?下面就讓我們一起來(lái)了解一下吧:
在shell腳本中編寫(xiě)腳本使用for循環(huán)一般是用于判斷輸入的用戶名是否存在,若是不存在的話那么創(chuàng)建該用戶并設(shè)置密碼,否則程序會(huì)繼續(xù)提示用戶,也就是提示重新輸入新建用戶名稱。
在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 “$@” --》取所有位置參數(shù),可以簡(jiǎn)寫(xiě)為for i
需要注意的是bash shell支持C式for循環(huán)。
示例代碼如下:
#!/bin/bash
j=$1
for ((i=1; i<=j; i++))
do
touch file$i && echo file $i is ok
done
$@: 所有位置變量的內(nèi)容
$#: 位置變量的個(gè)數(shù)
$0: 文件名
$*: 所有位置變量的內(nèi)容
for循環(huán)的一般代碼格式為:
for 變量名 in 列表
do
command1
command2
...
commandN
done
參考范例:
范例一
輸入代碼:
for loop in 1 2 3 4 5
do
echo "The value is: $loop"
done
輸出結(jié)果為:
The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5
范例二
若是編寫(xiě)腳本清空所有arp緩存記錄,示例代碼如下:
#!/bin/bash
for i in $(arp | tail -n +2|tr -s ' ' |cut -d' ' -f1)
do
arp -d $i
done
以上就是小編的分享了,希望能夠幫助到大家。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com