Is it possible to print a spinning cursor in a ter

2019-05-25 06:43发布

问题:

I have seen solutions which use c,python,ruby but bash. The closest possible design I found was using this ruby console solution

10.times {
  print "/"
  sleep(0.1)
  print "\b"
  print "-"
  sleep(0.1)
  print "\b"
  print "\\"
  sleep(0.1)
  print "\b"
  print "|"
  sleep(0.1)
  print "\b"
}

I want an effect something simillar to that.

回答1:

Spinners are nice, but if you really want a controllable progress meter that is aware of the IO you're dealing with, take a look at pv.

Here's a quick-and-dirty spinner. (Many nonstandard implementations of sleep will let you sleep for fractions of a second.)

Bash

spin() {
   local -a marks=( '/' '-' '\' '|' )
   while [[ 1 ]]; do
     printf '%s\r' "${marks[i++ % ${#marks[@]}]}"
     sleep 1
   done
 }

POSIX Sh

spin() {
  i=0
  marks='/ - \ |'
  while true; do
    if [ $# -lt 4 ]; then
      set -- "$@" $marks
    fi
    shift $(( (i+1) % $# ))
    printf '%s\r' "$1"
    sleep 1
  done
}


回答2:

same as @kojiro but without printf

spin() {
    local -a marks=( '/' '-' '\' '|' );
    while [[ 1 ]]; do
      echo -ne "${marks[i++ % ${#marks[@]}]}";
      sleep 1;
      echo -ne "\b";
    done;  
}


标签: bash shell unix