Search code examples
linuxbashunix

Simulating a spinner for progress in Bash


I am currently learning how to make scripts a bit more verbose. The below code shows a spinner. However, I am having difficulties modifying this spinner to have the words such as 'Downloading'. I want both the words and spinner to appear beside each other. I am not asking how to implement spinner for progress but how to concatenate with words. How could achieve this goal?

sp='/-\|'
sc=0
spin() {
   printf "\b${sp:sc++:1}"
   ((sc==${#sp})) && sc=0
}
endspin() {
   printf "\r%s\n" "$@"
}

until work_done; do
   spin
   some_work ...
done
endspin

Solution

  • While I admire the DIY spirit of Ed and Jakuje I also like to reuse other folks code. If you'd rather recycle than recreate consider Louis Marascio's spinner. I put his spinner() function into my shell library and it is easy to use:

    #!/bin/bash
    
    . lib.sh
    run_10s &
    echo -n wait
    spinner $!
    echo -e "\rdone"
    

    displays

    $ ./test_lib
    wait [/]
    

    for 10 seconds with the spinner spinning and then it clears that line left containing wait with the \r and you are left with just

    $ ./test_lib
    done
    

    on the screen.