jmginer
jmginer

Reputation: 381

Run script for each line of a file

I'm creating a litle script to run some command on all OpenVZ containers inside a node.

I read all OpenVZ containers ID, and I run some commands on all of them.

Instead in the listvz.txt file I have many IDs, the command only runs on the first, so the loop not run...

Any idea? Thanks!

#! /bin/bash
export PATH="/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin"

cat /dev/null > listvz.txt;
ls -r1 /vz/private > listvz.txt;

cat listvz.txt | while read line; do
echo FixMySQL in ${line}
vzctl exec ${line} /etc/init.d/mysql stop;
vzctl exec ${line} /etc/init.d/mysqld stop;
vzctl exec ${line} rm -rf /var/lib/mysql/mysql.sock;
vzctl exec ${line} /etc/init.d/mysql start;
vzctl exec ${line} /etc/init.d/mysqld start;
done

Result when I run:

[root@ovz ~]# sh mysql-check.sh
FixMySQL in 2168
/bin/bash: /etc/init.d/mysql: No such file or directory
/bin/bash: /etc/init.d/mysqld: No such file or directory
/bin/bash: /etc/init.d/mysql: No such file or directory
/bin/bash: /etc/init.d/mysqld: No such file or directory
[root@ovz1 ~]#

Only run on the CTID 2168, but there are much more CTIDs on the TXT file...

Fixed!

cat listvz.txt | while read line; do
echo FixMySQL in ${line} </dev/null
vzctl exec ${line} /etc/init.d/mysqld stop </dev/null
vzctl exec ${line} rm -rf /var/lib/mysql/mysql.sock </dev/null
vzctl exec ${line} /etc/init.d/mysqld start </dev/null
done

Upvotes: 1

Views: 2822

Answers (2)

Alok Tiwari
Alok Tiwari

Reputation: 364

Below code in Shell will work in order to run script for each line of a file

while IFS='' read -r line || [[ -n "$line" ]]; do
   #your code
done < "input_file"

Upvotes: 3

abadjm
abadjm

Reputation: 166

Oh!!!... IFS should be saved and restored, I prefer the following code:

while read LINE ; do
   # Do stuffs with $LINE
done < input.txt

Upvotes: 2

Related Questions