为文件的每一行运行脚本

时间:2014-02-18 11:21:21

标签: linux bash shell while-loop

我正在创建一个litle脚本,在节点内的所有OpenVZ容器上运行一些命令。

我读取了所有OpenVZ容器ID,并在所有这些容器上运行了一些命令。

而在listvz.txt文件中我有很多ID,命令只运行在第一个, 所以循环没有运行......

有什么想法吗? 谢谢!

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

我跑的结果:

[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 ~]#

仅在CTID 2168上运行,但TXT文件中有更多CTID ......

固定!

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

2 个答案:

答案 0 :(得分:3)

Shell中的以下代码将起作用,以便为文件的每一行运行脚本

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

答案 1 :(得分:2)

哦!!! ... IFS应该保存并恢复,我更喜欢以下代码:

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