Bash 脚本只读取文件的第一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15167689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash script only read the first line of the file
提问by garconcn
I wrote a script to ssh to remote server to find the disk usage of a user. However, this script can only read the first line, it doesn't continue on the other lines of the file. Anything wrong with my script? Thanks.
我写了一个脚本 ssh 到远程服务器来查找用户的磁盘使用情况。但是,此脚本只能读取第一行,不会继续读取文件的其他行。我的脚本有什么问题吗?谢谢。
#!/bin/bash
FILE="myfile.txt"
while read line; do
server=`echo $line|awk '{print }'`
cpid=`echo $line|awk '{print }'`
echo $server "---" $cpid "---" `ssh $server grep $cpid /var/cpanel/repquota.cache|awk '{print int(/1000) "MB"}'`
done < $FILE
myfile.txt contents:
myfile.txt 内容:
server1 user1
server2 user2
server3 user3
server1的USER1
服务器2 user2的
服务器3用户3
回答by chepner
The sshcall is inheriting its standard input from the while loop, which redirects from your file. This causes the sshcommand to consume the rest of the file. You'll need to use a different file descriptor to supply the readcommand:
该ssh调用从 while 循环继承其标准输入,该循环从您的文件重定向。这会导致ssh命令使用文件的其余部分。您需要使用不同的文件描述符来提供read命令:
#!/bin/bash
FILE="myfile.txt"
while read -u 3 server cpid; do
printf "$server---$cpid---"
ssh $server "grep $cpid /var/cpanel/repquota.cache | awk '{print int(/1000) \"MB\"}'"
done 3< $FILE
An alternative is to explicitly redirect input to sshfrom /dev/null, since you're not using it anyway.
另一种方法是将输入显式重定向到sshfrom /dev/null,因为无论如何您都没有使用它。
#!/bin/bash
FILE="myfile.txt"
while read server cpid; do
printf "$server---$cpid---"
< /dev/null ssh $server "grep $cpid /var/cpanel/repquota.cache | awk '{print int(/1000) \"MB\"}'"
done < $FILE
回答by Olaf Dietsche
First of all you can simplify your read loop to
首先,您可以将读取循环简化为
while read server cpid; do
echo $server "---" $cpid "---" `ssh ...`
done <$FILE
and save the parsing with awk. Another simplification is to save the call to grep and let awk do the search for $cpid
并用awk保存解析。另一个简化是保存对 grep 的调用并让 awk 搜索$cpid
ssh $server "awk '/$cpid/ {print int($3/1000) \"MB\"}' /var/cpanel/repquota.cache"
To your problem, I guess the sshcall doesn't return, because it waits for a password or something, and so prevents the loop to continue.
对于您的问题,我想该ssh调用不会返回,因为它会等待密码或其他内容,因此会阻止循环继续。

