0

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
  • 3
    How much of this script is actually relevant to the question? Do you just want to loop through lines of ip.txt and print a decreasing number? Commented Apr 22, 2015 at 14:52

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

can also use ((num--)) as an alternative to num=$((num-1))
True; ignoring what the OP would actually put in the body of the loop, everything else in my answer is POSIX-compliant, so I decided to keep the decrement operation compliant as well. If there are already bash-only features being used, there's no harm in using ((num--)) instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.