0

I'm trying to write a C program which can do the thing that many binaries such as package managers do in execution time. They change and add to the already outputted texts in terminal and it makes it fun. I want to know how can I do this, not only in C, maybe in bash or python. For example:

 program                  23 MiB   981 KiB/s 00:00 [######################] 100%

I mean a thing like this, the # grows up in downloading process.

Thanks for your cooperation.

zbx0310
  • 47
  • 4
  • Related: [dynamic display of a running process?](https://unix.stackexchange.com/questions/33868/dynamic-display-of-a-running-process) – steeldriver Jan 06 '21 at 17:12

1 Answers1

3

This is typically done by printing the complete line over and over again, using a carriage return instead of a line feed to return the cursor to the start of the line instead of the next. For example,

for i in {0..20}; do
  printf "ETA %2.1ds [%-20.${i}s]\r" "$((20-i))" "####################"
  sleep 1
done
printf "\n"

Carriage return is represented by \r in many C-inspired contexts.

More complex displays are typically constructed using a curses-style library. This is how many full-screen “text-mode” applications handle their output; see for example Midnight Commander.

Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164
  • One issue with this method is that the terminal helpfully forgets the overwritten text. But if you redirect the output to a file, it will appear to be one long line because \r is not a line terminator. Linux is relatively benign with long lines, but some older *nix commands used to have maximum line lengths. `[[ -t 1 ]]` can be helpful. – Paul_Pedant Jan 07 '21 at 12:49