-1
for i in {1..5};do
  echo $i/5
done

will echo

1/5
2/5
3/5
4/5
5/5

Is it possible to overwrite the previous echoed/printed line at every iteration? The program should echo 1/5 and then 2/5 instead of 1/5 and then 3/5, etc. At the end of the program only one line which contains 5/5 should be left.

Remi.b
  • 17,389
  • 28
  • 87
  • 168

2 Answers2

3

This can be achieved using a carriage return \r:

for i in {1..5}; do 
    printf "%d/5\r" "$i"
    sleep 1
done

I added a call to sleep so that you can see the terminal updating.

Note that you will need to print a newline at the end to avoid the terminal from overwriting the output.

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
2

To overwrite a line, use a carriage return, \r, and no linefeed.

Try, for example:

for i in {1..5}; do printf '\r%s/5' $i; sleep 0.1; done

The sleep command was added so that you have time see the numbers before they update again.

John1024
  • 109,961
  • 14
  • 137
  • 171