Code_Ed_Student
Code_Ed_Student

Reputation: 1190

Simulating a spinner for progress in Bash

I am currently learning how to make scripts a bit more verbose. The below code shows a spinner. However, I am having difficulties modifying this spinner to have the words such as 'Downloading'. I want both the words and spinner to appear beside each other. I am not asking how to implement spinner for progress but how to concatenate with words. How could achieve this goal?

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

Upvotes: 1

Views: 3730

Answers (3)

Vasiliy Kattouf
Vasiliy Kattouf

Reputation: 31

https://github.com/kattouf/ProgressLine

If someone looking for ready for use spinner solutions. I made a utility that allows to compactly track the progress(1) of execution for almost any command or script, perhaps it will be useful to you.

(1) Progress I mean duration and last line, percents in example is part of command output

demonstration

Upvotes: 0

chicks
chicks

Reputation: 2463

While I admire the DIY spirit of Ed and Jakuje I also like to reuse other folks code. If you'd rather recycle than recreate consider Louis Marascio's spinner. I put his spinner() function into my shell library and it is easy to use:

#!/bin/bash

. lib.sh
run_10s &
echo -n wait
spinner $!
echo -e "\rdone"

displays

$ ./test_lib
wait [/]

for 10 seconds with the spinner spinning and then it clears that line left containing wait with the \r and you are left with just

$ ./test_lib
done

on the screen.

Upvotes: 3

Jakuje
Jakuje

Reputation: 25966

You can do so like this

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

until work_done; do
   spin "Downloading"
   some_work ...
done
endspin

Upvotes: 7

Related Questions