Bash - get a reverse count of loop in output

2019-09-06 20:59发布

I want to get a count of loop in reverse in output to know how many loop remaining I miss to finish.

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

Something like this:

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

1条回答
淡お忘
2楼-- · 2019-09-06 21:46

You just need to know how many lines are in the stream in advance.

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

By the way, this shows the recommended way of iterating over a file; don't use a for loop.

查看更多
登录 后发表回答