bashshellunixprogress

Using Bash to display a progress indicator (spinner)


Using a bash only script, how can you provide a bash progress indicator?

For example, when I run a command from bash - while that command is executing - let the user know that something is still happening.


Solution

  • In this example using SCP, I'm demonstrating how to grab the process id (pid) and then do something while that process is running.

    This displays a simple spinnng icon.

    /usr/bin/scp me@website.com:file somewhere 2>/dev/null &
    pid=$! # Process Id of the previous running command
    
    spin[0]="-"
    spin[1]="\\"
    spin[2]="|"
    spin[3]="/"
    
    echo -n "[copying] ${spin[0]}"
    while [ kill -0 $pid ]
    do
      for i in "${spin[@]}"
      do
            echo -ne "\b$i"
            sleep 0.1
      done
    done
    

    William Pursell's solution

    /usr/bin/scp me@website.com:file somewhere 2>/dev/null &
    pid=$! # Process Id of the previous running command
    
    spin='-\|/'
    
    i=0
    while kill -0 $pid 2>/dev/null
    do
      i=$(( (i+1) %4 ))
      printf "\r${spin:$i:1}"
      sleep .1
    done