Using Bash to display a progress indicator

Pez Cuckow picture Pez Cuckow · Sep 19, 2012 · Viewed 95k times · Source

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

So I can run a command form bash, and while that command is executing let the user know that something is still happening.

Answer

Pez Cuckow picture Pez Cuckow · Sep 19, 2012

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 [email protected]: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 [email protected]: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