1

I have a script that counts down from 5 to 0:

for a in {5..0}; do echo $a | tr -d \\n; sleep 1; echo -e \\b | tr -d \\n; done

and tacking on tr -d just looks redundant and not very elegant to me. Is there a way to echo on one line without having to delete the newline?

Dan
  • 79
  • 9

1 Answers1

3

You can use -n flag with echo:

for a in {5..0}; do echo -n $a; sleep 1; echo -ne \\b; done

Or just use printf:

for a in {5..0}; do printf $a; sleep 1; printf \\b; done

Note that this will show invalid numbers if counting from numbers greater or equal to 10. You could use \r carriage return character and clear the line with space, for example assume maximum number of 20 digits and use left formatting and fill the line with spaces:

for a in {20..0}; do printf "\r%-20d" "$a"; sleep 1; done

With bash COLUMNS variable and with * parameter passed width specifier with printf you could fill the whole line with spaces:

for a in {20..0}; do printf "\r%-*d" "$COLUMNS" "$a"; sleep 1; done

Or use a ansi escape sequence to clear the line:

for a in {20..0}; do printf "\r\033[K%d" "$a"; sleep 1; done
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • What a sheepish way to learn about `echo -n`. Thank you very much, and for the other scripting improvements too! – Dan Dec 08 '19 at 13:47