简体   繁体   English

Bash脚本只读取文件的第一行

[英]Bash script only read the first line of the file

I wrote a script to ssh to remote server to find the disk usage of a user. 我写了一个ssh到远程服务器的脚本来查找用户的磁盘使用情况。 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. 谢谢。

#!/bin/bash
FILE="myfile.txt"
while read line; do
server=`echo $line|awk '{print $1}'`
cpid=`echo $line|awk '{print $2}'`
echo $server "---" $cpid "---" `ssh $server grep $cpid /var/cpanel/repquota.cache|awk '{print int($3/1000) "MB"}'`
done < $FILE

myfile.txt contents: myfile.txt内容:

server1 user1 server1 user1
server2 user2 server2 user2
server3 user3 server3 user3

The ssh call is inheriting its standard input from the while loop, which redirects from your file. ssh调用继承了while循环的标准输入,while循环从文件重定向。 This causes the ssh command to consume the rest of the file. 这会导致ssh命令占用文件的其余部分。 You'll need to use a different file descriptor to supply the read command: 您需要使用不同的文件描述符来提供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($3/1000) \"MB\"}'"
done 3< $FILE

An alternative is to explicitly redirect input to ssh from /dev/null , since you're not using it anyway. 另一种方法是显式地将输入从/dev/null重定向到ssh ,因为你还没有使用它。

#!/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($3/1000) \"MB\"}'"
done < $FILE

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. 并使用awk保存解析。 Another simplification is to save the call to grep and let awk do the search for $cpid 另一个简化是保存对grep的调用,让awk搜索$cpid

ssh $server "awk '/$cpid/ {print int(\$3/1000) \"MB\"}' /var/cpanel/repquota.cache"

To your problem, I guess the ssh call doesn't return, because it waits for a password or something, and so prevents the loop to continue. 对于你的问题,我猜ssh调用没有返回,因为它等待密码或其他东西,因此阻止循环继续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM