1

I'm trying to write a script where I want to make a countdown of three seconds (probably with the sleep command), but every second I want to display the text "break".

After every second, I want to display a countdown next to the word "break", but the line of text should stay in place. The word "break" must stay in one place; only the number should change.

Sinister Beard
  • 3,570
  • 12
  • 59
  • 95
Jim Peeters
  • 2,573
  • 9
  • 31
  • 53

2 Answers2

1

You can use ANSI terminal control sequences. Like this:

# Save the cursor position
echo -en "\033[s";

for i in {3..1} ; do

    echo -n "break $i"
    sleep 1

    # Restore the cursor position
    echo -en "\033[u";

done

# Print newline at the end
echo

If you want the last break 1 to disappear from screen then change the last line to

# Clear the line at the end
echo -en "\033[K"
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
1

In bash, you can use a for loop, and the character \r to move the cursor back the the beginning of the line:

for ((i=3; i; --i)) ; do
    printf 'break %d\r' $i
    sleep 1
done
choroba
  • 231,213
  • 25
  • 204
  • 289