Spinner

Stylish 0 Tallied Votes 252 Views Share

Here is a little spinner thing for the command line, used when your current bash script is waiting on a background/system process.

The weird character is ^H or a backspace.

## This is similar to what FreeBSD does when it is booting
### some command &
### do_progress_spin_l $!
# A small "asterik" like thing will spin until the process is complete
#+ (when ps ax | grep PID no longer finds anything)
do_progress_spin_l()
{
  ## The characters to use
  # These will be overlapped via ^H
  ICON[0]="/"
  ICON[1]="-"
  ICON[2]="\\"
  ICON[3]="|"

  ## The process we wish to monitor
  PROCESS=$1

  ## Initialize count value
  # print out first icon
  icon_num=0
  echo -n ${ICON[$icon_num]}

  ## While the process exists in ps ax, do this loop
  while ( ps ax | grep $PROCESS | grep -v "grep" 1>/dev/null )
  do
    ## If our count is bigger than 3 (our highest number icon)
    # reset it to 0
    if [ "$icon_num" -gt "3" ]; then
    	icon_num=0
    fi

    ## ^Hnew_icon
    echo -n ${ICON[$icon_num]}
    icon_num=`expr $icon_num + 1`

    sleep 0.5
#    sleep 1
  done

  ## Little clean-up. Print done and a new line
  echo -n "... Done"
  echo ""
}
Stylish 1 Junior Poster

Wrong category issue was fixed. Hurrah!

cfajohnson 7 Shell scripter and author

If you want to slow down the loop increase the argument to sleep, don't call an external command for integer arithmetic.

icon_num=$(( $icon_num + 1 ))

That's a very complicated script for a simple task; try this:

some_command &
pid=$!

delay=.25
string='|/-\'
while :
do
  temp=${string#?}
  printf " %c\r" "$string"
  string=$temp${string%"$temp"}
  sleep $delay ## requires sleep that accepts decimals
done &
wait $pid && kill $!
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.