Differences between revisions 8 and 10 (spanning 2 versions)
Revision 8 as of 2013-07-26 23:08:41
Size: 1228
Comment:
Revision 10 as of 2015-05-15 07:51:54
Size: 1237
Editor: geirha
Comment: single quotes to be sure a backslash remains a backslash.
Deletions are marked like this. Additions are marked like this.
Line 6: Line 6:
i=1
sp="/-\|"
echo -n ' '
while true
do
    printf "\b${sp:i++%${#sp}:1}"
i=0
sp='/-\|'
n=${#sp}
printf
' '
while true; do
    printf '\b%s' "${sp:i++%n:1}"
Line 34: Line 34:
sp="/-\|" sp='/-\|'

Can I do a spinner in Bash?

Sure!

i=0
sp='/-\|'
n=${#sp}
printf ' '
while true; do
    printf '\b%s' "${sp:i++%n:1}"
done

Each time the loop iterates, it displays the next character in the sp string, wrapping around as it reaches the end. (i is the position of the current character to display and ${#sp} is the length of the sp string).

The \b string is replaced by a 'backspace' character. Alternatively, you could play with \r to go back to the beginning of the line.

If you want it to slow down, put a sleep command inside the loop (after the printf).

A POSIX equivalent would be:

sp='/-\|'
printf ' '
while true; do
    printf '\b%.1s' "$sp"
    sp=${sp#?}${sp%???}
done

If you already have a loop which does a lot of work, you can call the following function at the beginning of each iteration to update the spinner:

sp='/-\|'
sc=0
spin() {
   printf "\b${sp:sc++:1}"
   ((sc==${#sp})) && sc=0
}
endspin() {
   printf "\r%s\n" "$@"
}

until work_done; do
   spin
   some_work ...
done
endspin

A similar technique can be used to build progress bars.


CategoryShell

BashFAQ/034 (last edited 2023-10-26 18:03:57 by emanuele6)