Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating rotating circle using characters |, /, \,- in shell script

Tags:

shell

I want to write a shell script which does installation related task. I want to show some icon like rotating circle by printing characters |, /, \, -. Once the installation completes this circle will disappear. Any help on this would be appreciated.

like image 592
user419534 Avatar asked May 06 '12 11:05

user419534


2 Answers

Building on Marc B's answer, here's a simple demo:

spin () {

  chars="| / – \\"

  rotations=3

  delay=0.1

  for i in `seq 0 $rotations`; do

    for char in $chars; do 

      echo -ne $char
      sleep $delay
      echo -ne '\b'

    done

  done

}

Paste it in your terminal and type 'spin'.


Update: this version works in both bash and zsh.

spin () {

  char=( \| / – \\ )

  charLastIndex=3

  rotations=3

  delay=0.1

  for i in `seq 1 $rotations`; do

    for j in `seq 0 $charLastIndex`; do 

      echo -n ${char[$j]}
      sleep $delay
      echo -ne '\b'

    done

  done

}

Update: liori's version works in multiple shells.

spin () {
  rotations=3
  delay=0.1
  for i in `seq 0 $rotations`; do
    for char in '|' '/' '-' '\'; do
      #'# inserted to correct broken syntax highlighting
      echo -n $char
      sleep $delay
      printf "\b"
    done
  done
}
like image 192
Dagg Nabbit Avatar answered Sep 27 '22 22:09

Dagg Nabbit


The accepted solution is overly complicated. You can just do:

while sleep 1; do 
  i=$((++i%4 + 2)); 
  printf '\b|/-\' | cut -b 1,$i | tr -d '\n';
done

(Note that subsecond sleeping is not portable, and neither is seq.)

like image 31
William Pursell Avatar answered Sep 28 '22 00:09

William Pursell