How to print out to the same line, overriding previous line?

bash, shell

Solution

Use the special character `\r`. It returns to the beginning of the line without going to the next one.

for i in {1..10} ; do
    echo -n '['
    for ((j=0; j<i; j++)) ; do echo -n ' '; done
    echo -n '=>'
    for ((j=i; j<10; j++)) ; do echo -n ' '; done
    echo -n "] $i"0% $'\r'
    sleep 1
done

Problem

Sometimes I see some commands in the terminal that print results to stdout but in the same line. For example wget prints an arrow like below: ``` 0[=> ]100% 0[ => ]100% 0[ => ]100% 0[ => ]100% 0[ =>]100% ``` but it is printed out to the same line so it looks like the arrow is moving. How can I achieve the same thing in my programs using bash or sh? Do I need to use other tools? UPDATE: I know I mentioned wget, which comes by default in linux, GNU based unices ... Is there a general approach that works on BSDs too? (like OSX) -> OK, If I use bash instead of sh then it works :)

Original source

Related problems