while和for對文件的讀取是有區別的:
1. for對文件的讀是按字符串的方式進行的,遇到空格什么后,再讀取的數據就會換行顯示
2. while對文件讀是逐行讀完后跳轉到下行,while相對for的讀取很好的還原數據原始性
正常情況下我們按行讀取文件都直接用while來實現的,但是在某些特殊情況下使用while可能會出現問題(例如
while循環里嵌套sshpass命令時,while在從文件讀取數據時,只讀取第一行數據就自動退出了,並且退出狀態為0),此時我們就必須要使用for循環來逐行從文件讀取數據。
目前有info.txt這個文件,里面存儲了以空格分割的IP、用戶名、密碼等信息。
|
[root@imzcy ~]# cat info.txt
192.168.1.1 zhangsan 123456
192.168.1.2 lisi 111111
192.168.1.3 wangwu 22222
|
|
1.我們按照while的習慣來寫腳本嘗試使用for讀取文件每行數據(當然下面這個腳本是有問題的)。
|
[root@imzcy ~]for i in $(cat info.txt);do echo $i ;done
|
for循環會以空格分割讀入的數據,所以輸出為:
192.168.1.1
zhangsan
123456
192.168.1.2
lisi
111111
192.168.1.3
wangwu
22222
|
2.shell下使用for循環來按行從文件讀入數據(每次讀入一整行數據)
|
#!/bin/bash
f=/root/info.txt
l=`cat $f |wc -l`
for i in `seq 1 $l`;
do
cat $f |head -n $i |tail -n 1
sleep 1
done
|
執行結果為:
192.168.1.1 zhangsan 123456
192.168.1.2 lisi 111111
192.168.1.3 wangwu 22222
cat $f |head -n $i |tail -n 1 獲取某一行
|
while循環讀方式
|
#!/bin/bash
cat filename | while read line;do
echo $line
done
|
192.168.1.1 zhangsan 123456
192.168.1.2 lisi 111111
192.168.1.3 wangwu 22222
|
while循環讀方式2
|
#/bin/sh
while read line;do
echo $line
done < filename
|
|
while 死循環
|
while [ "1" = "1" ]
do
#do something
done
|
|
將info.txt文件中存儲的信息使用逗號分隔,然后使用for循環讀取文件內容
|
cat info.txt
192.168.1.1,zhangsan,123456
192.168.1.2,lisi,111111
192.168.1.3,wangwu,22222
ips=`cat info.txt`
for ip in $ips;do
echo $ip
ip_info=(${ip//,/ })
if [ ${#ip_info[@]} -eq 3 ];then
#do something
fi
done
|