Writing always in the same line in bash

Have you ever wanted to write a bunch of words just in the same line over and over again?
Many applications, like encoders or converters, do that in order to show dynamic information to the user without filling up the screen (and thus the terminal buffer).

Here is how you can do it easily in bash.

The code is quite simple:

while :; do
echo -n -e "\r$(date)"
sleep 1
done

The trick consists of three parts:

  1. -n: we tell echo that we don’t want it to insert any new line character at the end of the string.
  2. -e: we tell echo to translate any escaped sequence to the corresponding control character.
  3. we use \r, which is simply a return carriage control character; this way, we always print in the same line over and over.
  4. With the same approach we can develop a fancy text progress bar.
    For example, here is a nice cp command equipped with a simple progress bar:

    #!/bin/bash

    bar_width=30
    tick=0.2

    if [ $# -ne 2 ]; then
        cat << EOM
    $0: missing file operand
    Use $0 filein fileout.
    EOM
        exit 1
    fi

    function draw_progressbar() {

    # parameters:
    # $1 - actual size
    # $2 - final size

        local part=$1
        local place=$((part*bar_width/$2))
        local i

        echo -en "\r$((part*100/total))% ["
       
        for i in $(seq 1 $bar_width); do
            [ "$i" -le "$place" ] && echo -n "#" || echo -n " ";
        done
        echo -n "]"

    }

    total=$(stat -c "%s" $1)

    cp $1 $2 &

    sleep $tick;
    while fuser -s $2; do
        draw_progressbar $(stat -c "%s" $2) $total
        sleep $tick;   
    done

    draw_progressbar $(stat -c "%s" $2) $total
    echo ""

    References:

    None
    A comma-separated list of terms describing this content. Example: funny, bungee jumping, "Company, Inc.".