0

My sh is bash. I need a percentile progress indicator for my 0~9999 'for' loop... So I use this lines within the loop, but the output is very strange.

#!/bin/bash
declare -i percentile
for((i=0;i<=9999;i++))
do
        percentile=($i+1)%100
        if [ "$percentile" == 0 ];then
                echo -ne $((($i+1)/100))\%\r
        fi
done
echo -n '\n'

What I want to see is it outputs '1%' and then replace this line with '2%' and '3%' ... but not '1%', '2%', '3%', ... line by line.

After execute this .sh file, what displayed on the terminal is

-ne 1%r
-ne 2%r
-ne 3%r
-ne 4%r
-ne 5%r
-ne 6%r
-ne 7%r
-ne 8%r
-ne 9%r
-ne 10%r
...

The bash just didn't recognize the '-ne' option and the escaped '\r' for 'echo' command, what should I do to solve this problem?

  • 1
    And your sh is? – heemayl Feb 13 '17 at 3:53
  • Your script works fine for me. Could be different shells. What about using printf instead? – Sparhawk Feb 13 '17 at 3:56
1

If you have to use echo, then try with quoted return, ie '\r', not just \r. The whole line is then:

echo -ne $((($i+1)/100))\%'\r'

And take a look at Why is printf better than echo?

1

I don't think you're using bash because both the -n and -e flags are usually understood by bash's echo utility.

Make sure that you run the script by either explicitly specifying bash as the interpreter,

$ bash ./script.sh

or by making it executable and running it,

$ chmod +x ./script.sh
$ ./script.sh

Your arithmetic operations in the script are also wrong (when calculating percentile). bash performs arithmetic substitutions in $(( ... )) and arithmetic evaluation in (( ... )).

Here's an alternative implementation:

iter=70500

for(( i = 1; i <= iter; i++ )); do
    if ! (( i % (iter/100) )); then
        printf '\r%d%%' "$(( (100*i)/iter ))"
    fi
done

echo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.