Reputation: 125
I have a spinner on the same line as some output, and when a process is done, I'd like to remove the spinner from the output and move to the next line. The part that troubles me is how to remove it when it's done.
spinner() {
local pid=$!
spin='-\|/'
i=0
while kill -0 $pid 2>/dev/null; do
i=$(((i + 1) % 4))
printf "%c" "${spin:$i:1}"
printf "\b"
sleep .1
done
}
echo "Call some process"
command &
spinner
echo "Done"
The above outputs (note that the spinner stays on the first line in its last position):
Call some process \
Done
Upvotes: 1
Views: 626
Reputation: 27245
I'd like to remove the spinner from the output and move to the next line
Overprint it with a space and then output a newline.
By the way: In my terminal the spinner runs a lot smoother if you use a single printf
for %c
and \b
:
spinner() {
local pid=$!
local spin='-\|/'
local i=0
while kill -0 $pid 2>/dev/null; do
(( i = (i + 1) % 4 ))
printf '%c\b' "${spin:i:1}"
sleep .1
done
echo ' '
}
In case you don't want to move to a new line, but rather want to clear it immediately while keeping the cursor in the same line you can use printf ' \r'
instead.
Upvotes: 2
Reputation: 141493
how to remove it when it's done.
So just print a space.
sleep .1
done
printf " "
}
Upvotes: 1