Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script only read the first line of the file

Tags:

bash

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

like image 460
garconcn Avatar asked Mar 01 '13 22:03

garconcn


2 Answers

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
like image 194
chepner Avatar answered Sep 22 '22 10:09

chepner


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.

like image 32
Olaf Dietsche Avatar answered Sep 20 '22 10:09

Olaf Dietsche