In writing a script which iterated over a matrix taking over a minute for each ‘column’ of the matrix I decided it would be much more meaningful to see the progress as a percentage. The following snipped of code does this for you.
The line:
echo -n "$((${NUMBER}*100/${MAXPROG})) % "
calculates the percentage of NUMBER/MAXPROG which in this case was a number that indicated the progress across an ordered and evenly spaced set of numbers. Your application will of course vary but NUMBER should be something that indicates how far along the process is as a percent where as MAXPROG is some value that indicates the maximum amount of progress. How you calculate NUMBER will depend on your application and the accuracy and ease of calculating the progress is of course your real task.
The echo -n means that the percentage is printed without moving the cursor to the next line. The series of spaces after the percentage symbol and the double quotes which cause these spaces to be printed. Are there to cope with a situation where you are resetting the percentage or where NUMBER doesn’t always follow a strict numerical sequence. i.e. having shown 15% progress you suddenly estimate that it was actually only 5%. In this case it may be that you increased MAXPROG.
In the script below I calculated MAXPROG as the number of items in the list. Your mechanism will vary. Using a number as the value from the list will only result in a true percentage of progress in a situation where the list is a list of incrementing integers from 1. i.e. counting. You will have to calculate NUMBER in a way that is appropriate for your application as well and operate the loop in whatever way makes sense for your situation.
The echo -n R | tr ‘R’ ‘\r’ is really not elegant. It is just a way of me printing a carriage return which is portable. A carriage return code was used on early electrical printers as a instruction to move the print head back to the left and start again at the first column. It moves the cursor to the left and again due to the -n flag does not move the cursor to a new line. As a result the next time you go around your loop the percentage will be printed over the top of the first percentage.
The final echo statement moves the cursor to a new line so that your prompt is not printed over the top of the final 100%.
#!/bin/bash
LIST="1 2 3 4 5"
MAXPROG=$(echo ${LIST} | wc -w)
for NUMBER in ${LIST};
do
echo -n "$((${NUMBER}*100/${MAXPROG})) % "
echo -n R | tr 'R' '\r'
sleep 2
done
echo
Recent Comments