0

I am thinking of writing a simple shell program that will show an output in the console about the percentage work completed. something like thiss:-

2%==>

which will increase the arrow with respect to the work done. I donot want to print the loader every time in a new line. what should be my approach?'
*I often see this thing is used in wget and similar commands
TIA

isnvi23h4
  • 1,910
  • 1
  • 27
  • 45

1 Answers1

1

To update the line the cursor is on, send a CR ("carriage return", \r) to send ("return") the cursor to the beginning of the existing line, from which you can print new contents. Contrast this to the newline (\n), which moves the cursor to a new line.

To see this in action, try running the following:

printf '%s\r' "Existing contents being written here"
sleep 1
printf '%s\r' "New contents being written here     "
sleep 1
printf '%s\n' "Writing final contents and moving to a new line"
printf '%s\n' "This is written to a second line."

Note how the second line has some extra whitespace on the end; this padding is there to make sure that the end of the original line's contents are overwritten.


That said, if you just want a status bar already built for you, there are numerous solutions for that already:

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • exactly the thing that is was looking for, is the %s doing the carriage return? thanks a lot – isnvi23h4 Sep 28 '15 at 17:19
  • 1
    No, it's the `\r`; the `%s` is the placeholder that specifies where your text (given in the next argument) will go. – Charles Duffy Sep 28 '15 at 17:21
  • ...so, `printf 'foo\r'` will print `foo`, then send the cursor back to the beginning of the same line, ready to have something else written over it. The purpose of the `%s` placeholder and then your string in a separate argument is so you don't need to make sure your string doesn't contain other contents special to printf. (If you want backslash-escapes processed but nothing else, consider `%b` instead). – Charles Duffy Sep 28 '15 at 17:23