Bash script only read the first line of the file

I wrote a script for ssh on a remote server to find the disk usage by the user. However, this script can only read the first line, it does not continue in other lines of the file. Is there something 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 

The contents of myfile.txt:

server1 user1
server2 user2
server3 user3

+6
source share
2 answers

The ssh call inherits its standard input from the while loop, which is redirected from your file. This causes the ssh command to consume the rest of the file. To provide the read command, you need to use a different file descriptor:

 #!/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 are 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 
+8
source

First of all, you can simplify your reading cycle to

 while read server cpid; do echo $server "---" $cpid "---" `ssh ...` done <$FILE 

and save the parsing with awk. Another simplification is to save the grep call and let awk search for $cpid

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

To your problem, I think the ssh call does not return because it is waiting for a password or something else, and therefore prevents the loop from continuing.

+1
source

All Articles