Home > OS >  Show progress while sleep in bash
Show progress while sleep in bash

Time:09-22

I wrote a simple script which must show progress while user waiting. But I get infinitive loop and seems sleep not working. What wrong in this code?

#!/bin/bash

spinner=(
"Working    "
"Working.   "
"Working..  "
"Working... "
"Working...."
)

while sleep 10 
  do
    for item in ${spinner[*]}
      do
        echo -en "\r$item"
        sleep .1
        echo -en "\r              \r"
      done
  done

CodePudding user response:

One idea:

  • using the bash (system) variable SECONDS to measure our 10 seconds
  • using a tput code for ovewriting a line
  • eliminating the spinner[] array (since the only difference in values is the number of trailing periods)

EraseToEOL=$(tput el)
max=$((SECONDS   10))              # add 10 seconds to current count

while [ $SECONDS -le ${max} ]
do
    msg='Waiting'
    for i in {1..5}
    do
        printf "%s" "${msg}"
        msg='.'
        sleep .1
    done
    printf "\r${EraseToEOL}"
done
printf "\n"

A small change to OP's current code using the max/SECONDS approach:

spinner=(
"Working    "
"Working.   "
"Working..  "
"Working... "
"Working...."
)

max=$((SECONDS   10))

while [[ ${SECONDS} -le ${max} ]]
do
    for item in ${spinner[*]}
    do
        echo -en "\r$item"
        sleep .1
        echo -en "\r              \r"
    done
done

CodePudding user response:

Use the in/decrement variable i to put out the array...

#!/bin/bash

countdown(){
spinner=(
"Working    "
"Working.   "
"Working..  "
"Working... "
"Working...."
)

i=4

if [ ${i} -lt 5 ]
then
 while true
  do
   for i in ${i}
    do
     printf "%s    \t" ${spinner[i]}
     sleep .1
     printf "\r"
     sleep .1
     if [ ${i} -eq 0 ]
      then
       # Here you can clean up or do what to do at zero count
       printf "\n"
       unset i
       unset spinner
       return 0 # Can be used in ${?} from parent bash
     else
      i=$((${i}-1))
    fi
  done
 done
return 1 # Should never be executed
fi
}

# A funny cd ;-)
cd(){
countdown && printf "%s\n" "DONE changing to "${1} # Gives out if return is 0 (${?})
unset cd
cd ${1}
}
#
cd ~
  • Related