简体   繁体   中英

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. 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:

server1 user1
server2 user2
server3 user3

The ssh call is inheriting its standard input from the while loop, which redirects from your file. This causes the ssh command to consume the rest of the file. You'll need to use a different file descriptor to supply the read command:

#!/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.

#!/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. Another simplification is to save the call to grep and let awk do the search for $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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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