【问题标题】:Bash - get a reverse count of loop in outputBash - 在输出中获取循环的反向计数
【发布时间】:2015-04-22 14:48:08
【问题描述】:

我想在输出中反向计算循环数,以了解我错过完成的剩余循环数。

#!/bin/bash
datenow=$(date +"%F")
logfile="table-"$datenow".log"
rm -f table.sql
mysql --login-path=myloginpath -h xhost -N -e \
"select count(*) from database.table a where a.field = 0;" | tee -a     $logfile
mysqldump --login-path=myloginpath-h xhost database table > table.sql
read -p "Insert Host Separated by comma ',' : " localcs
mysql --login-path=myloginpath -h xhost -N -e \
"select n.ipaddress from database.hosts n where n.hosts in ($localcs);"  > ip.txt
for ip in $(cat ip.txt);
do
mysql --login-path=myloginpath -h $ip "database" < "table.sql"
echo $ip  | tee -a $logfile && mysql --login-path=myloginpath -h $ip -N -e \
"select count(*) from database.table a where a.field = 0;" | tee -a $logfile
done

类似这样的:

100
(mysql output)
99
(mysql output)
98
(mysql output)
.....

【问题讨论】:

  • 这个脚本有多少实际上与问题相关?您是否只想遍历ip.txt 的行并打印一个递减的数字?

标签: mysql linux bash shell


【解决方案1】:

您只需要提前知道流中有多少行。

num=$(wc -l < ip.txt)
while read -r ip; do
    # Do your work, use $num as needed

    # Then decrement num
    num=$((num-1))
done < ip.txt

顺便说一下,这显示了迭代文件的推荐方式;不要使用for 循环。

【讨论】:

  • 也可以使用((num--)) 替代num=$((num-1))
  • 真;忽略 OP 实际放入循环体中的内容,我的答案中的其他所有内容都符合 POSIX,因此我决定也保持减量操作符合要求。如果已经使用了bash-only 功能,那么改用((num--)) 并没有什么坏处。
猜你喜欢
  • 2017-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-26
  • 2011-03-10
  • 2021-11-06
  • 2013-06-01
相关资源
最近更新 更多