LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Strange behaviour in bash - while loop (https://www.linuxquestions.org/questions/programming-9/strange-behaviour-in-bash-while-loop-560210/)

Guttorm 06-08-2007 10:08 AM

Strange behaviour in bash - while loop
 
Hi

I have a textfile with servers that is being read by a backup script in a while loop. Here is it, simplified a bit:

servers.txt:
Quote:

server1 database1
server2 database2
and so on...

This works fine:
Code:

cat servers.txt |
while read line
do
  server=$(echo $line |awk '{print $1}')
  database=$(echo $line |awk '{print $2}')
  echo "Server: $server - Database: $database"
done

Then I add code that actually do something:
Code:

cat servers.txt |
while read line
do
  server=$(echo $line |awk '{print $1}')
  database=$(echo $line |awk '{print $2}')
  echo "Server: $server - Database: $database"
  ssh $server "mysqldump -u root --password=mysecret $database" >$database.sql
  echo "Ok"
done

The problem is, when I add the ssh command, the script stops after the first line. The database dump is made, "Ok" is printed, but the loop stops. Somehow the ssh command messes up the reading of the textfile it seems.

Is there perhaps a different way to read thru a textfile, without using pipes?

avatarez 06-08-2007 10:23 AM

I dont know if this is the best way, but this is how i do it and works for me

(
read LINE;

while [ -n "$LINE" ]
do

# do the same things you were doing before

read LINE;
done
) < servers.txt

Guttorm 06-08-2007 10:33 AM

Thank you. I tried it, but it behaves the same. Without the ssh command, it works fine, but with it, it stops after the first line.

I guess I have to read the textfile into an array and then loop thru it, as it seems the piping gets messed up by the ssh. So I'll try to change it to an array then.

druuna 06-08-2007 12:15 PM

Hi,

ssh inherits stdin, which makes the pipe (cat ... | while ...) useless. Use ssh's -n option to get around this behavior. I.e:

Code:

cat servers.txt |
while read line
do
  server=$(echo $line |awk '{print $1}')
  database=$(echo $line |awk '{print $2}')
  echo "Server: $server - Database: $database"
  ssh -n $server "mysqldump -u root --password=mysecret $database" >$database.sql
  echo "Ok"
done

Hope this helps.

Guttorm 06-08-2007 02:11 PM

Thank you!

I had already changed the script to read into an array. It was a bit of work since variables read in a pipe would lose their value when done. So I changed it to ksh and it worked.

Your solution is a lot simpler, and also, now I understand why it behaved the way it did. :)


All times are GMT -5. The time now is 01:02 AM.