DEV Community

Richard Lenkovits
Richard Lenkovits

Posted on

Simple bash loading animation

I was looking for a simple way to achieve a basic load icon that ticks after a piece of text in bash, but there was noting I could just easily copy paste. Now I'll provide one for you, no shenanigans, no messing around.

Short story

I've found this one, Silejonu's solution on Github but this is rather a module than something you can copy paste, and sometimes you don't want to add whole dependencies, just a piece of logic.

So here it is:

function loading_icon() {
    local load_interval="${1}"
    local loading_message="${2}"
    local elapsed=0
    local loading_animation=( '—' "\\" '|' '/' )

    echo -n "${loading_message} "

    # This part is to make the cursor not blink
    # on top of the animation while it lasts
    tput civis
    trap "tput cnorm" EXIT
    while [ "${load_interval}" -ne "${elapsed}" ]; do
        for frame in "${loading_animation[@]}" ; do
            printf "%s\b" "${frame}"
            sleep 0.25
        done
        elapsed=$(( elapsed + 1 ))
    done
    printf " \b\n"
}

loading_icon 60 "I'm loading!"
Enter fullscreen mode Exit fullscreen mode

And here's what it looks like:

bash loading animation

Limitations

  • Shows a given loading_message and after it a small loading icon for the provided load_interval seconds.
  • After the provided time elapsed the last character of the loading icon is erased and a new line is started (this can be changed by updating printf " \b\n").

You can get more animation ideas from Silejonu, bash_loading_animations file, all you have to do is to replace the loading_animation variable in the script (don't forget to remove the first element, the interval number).

Enjoy! ^^

Top comments (0)