I found this for BASH, but I want to do the same thing with shell (#!/bin/sh
).
The twist is to make it a timer also, so like wait 60 seconds for example until it ends.
I found this for BASH, but I want to do the same thing with shell (#!/bin/sh
).
The twist is to make it a timer also, so like wait 60 seconds for example until it ends.
The solution is this:
Fadi's own solution is helpful (and comes by courtesy of Adam Katz's comment on the linked answer), but comes with 2 caveats:
\r
, only works at the beginning of a line.sleep
only supports integral seconds.It may also not be readily obvious where to test for whether the operation is done and how to exit the two loops vs. how to use a spinner as a background job, while waiting for a blocking command to finish.
The following snippets address these issues; they use
\b
(backspace) rather than\r
, which allows the spinner to be displayed with preceding text, if desired:Asynchronous case (poll for completion):
If you're waiting for completion of a process asynchronously (by checking for completion periodically, in a loop):
The above, due to printing the
\b
char. after the spinner char., displays the cursor behind the spinner char; if that is aesthetically undesirable, use the following variation to display the cursor on top of the spinner:I0_ol suggests using
tput civis
andtput cnorm
to hide the cursor temporarily; while not strictly POSIX-compliant (POSIX mandates only 3tput
operands:clear
,init
, andreset
), it does appear to be supported by most modern terminal emulators.A more complete example with configurable timeout and sleep interval (note that the timeout enforcement will not be exact, as the time it takes to process each loop iteration is not taken into account; in
bash
, you could simply reset special var.SECONDS
before the loop starts and then check its value):Synchronous (blocking) case:
If you're waiting for a lengthy synchronous (blocking) command to complete, the spinner must be launched as a background job, which you then terminate once the blocking call has completed.