本文介绍了在while循环bash脚本中读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这段代码可以读取/etc/passwd的示例文件:
I've got this code which reads an example file of /etc/passwd:
#!/bin/bash
OLDIFS=$IFS
IFS=$'\n'
while read linea resto
do
echo $linea
echo $resto
if [[ $(echo $linea | cut -d: -f6 | egrep -c 'al-03-04') == 1 ]]
then
finger $(cut -d: -f1) 2> fich
if [[ $(egrep -c fich) == 1 ]]
then
echo $(echo $linea | cut -d: -f1). Inactive user
else
echo $(echo $linea | cut -d: -f1). Active user
fi
fi
done < <(cat fichpasswd)
IFS=$OLDIFS
这是/etc/passwd的示例文件:
and this is the example file of /etc/passwd:
jfer:x:5214:1007:Javier Lopez,,,:/home/al-03-04/jfer:/bin/bash
jperez:x:10912:1009:Juan Perez,,,:/home/al-03-04/jperez:/bin/bash
mfernan:x:10913:1009:Manuel Fernandez,,,:/home/al-02-03/mfernan:/bin/bash
问题在于while循环仅读取第一行,而忽略其他行.脚本的输出为:
The problem is that the while loop only reads the first line, ignoring the others. The script's output is:
jfer:x:5214:1007:Javier Lopez,,,:/home/al-03-04/jfer:/bin/bash
jfer. Active user
推荐答案
您可以尝试以下方法:
#!/bin/bash
FILE="test.txt"
while IFS=":" read -a data; do
echo "${data[@]}"
if [[ $(echo ${data[5]}|egrep -c 'al-03-04') -eq 1 ]]; then
if [[ $(finger "${data[0]}" 2>&1) =~ "no such user" ]]; then
echo "${data[0]}. Inactive user"
else
echo "${data[0]}. Active user"
fi
fi
done < "$FILE"
这是输出:
ineumann ~ $ cat test.txt
ineumann:x:5214:1007:Javier Lopez,,,:/home/al-03-04/jfer:/bin/bash
jperez:x:10912:1009:Juan Perez,,,:/home/al-03-04/jperez:/bin/bash
mfernan:x:10913:1009:Manuel Fernandez,,,:/home/al-02-03/mfernan:/bin/bash
ineumann ~ $ ./test.sh
ineumann x 5214 1007 Javier Lopez,,, /home/al-03-04/jfer /bin/bash
ineumann. Active user
jperez x 10912 1009 Juan Perez,,, /home/al-03-04/jperez /bin/bash
jperez. Inactive user
mfernan x 10913 1009 Manuel Fernandez,,, /home/al-02-03/mfernan /bin/bash
对脚本的一些评论:
- 无需使用
cat
循环读取文件. -
finger $(cut -d: -f1) 2> fich
:cut
需要输入.无需使用临时文件来捕获finger
的输出(而且这不是线程安全的). - 当您选择正确的
IFS
将行分成多个部分时,无需在脚本中使用cut
.对于您而言,我认为最明智的选择是:
. - 您只能使用语法
while IFS=':' read; do ...; done
在循环内部更改IFS
.无需用OLDIFS
重新分配IFS
. - 您还可以使用
while IFS=':' read var1 var2 var3 trash; do ...; done
语法来避免将数组与read -a
一起使用(但是我更喜欢使用我在脚本版本中编写的数组).
- No need to use
cat
to read your file in a loop. finger $(cut -d: -f1) 2> fich
:cut
need an input. And no need to use a temporary file to catch the output offinger
(moreover this is not thread safe).- No need to use
cut
in your script when you choose the rightIFS
to split a line in multiple parts. In your case, I think the smartest choice would be:
. - You can change the
IFS
only inside the loop with the syntaxwhile IFS=':' read; do ...; done
. No need to re-assignIFS
withOLDIFS
. - You can also use the
while IFS=':' read var1 var2 var3 trash; do ...; done
syntax to avoid to use an array withread -a
(but I'd prefer to use an array as I wrote in my version of your script).
这篇关于在while循环bash脚本中读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!