Sometimes in BASH/SH scripts we run some program, commands, or another script that takes a long time to execute without any periodic output to the terminal screen. In that case the user who launched the script may get worried by the screen being motionless (maybe it's hung?). And even the message "Please wait" doesn't put their mind at ease.
So let's make some kind of indicator that shows something is happening. Of course, we can't build a real progress bar - we have no way of seeing how much of the long command's work has been completed. But even asterisks or dashes being drawn will reassure the user a little - "it's working, it hasn't hung."
Below is a piece of code with comments that does exactly this.
#!/bin/sh
# Here we declare a function that will be started
# before the long command is called
timer_func() {
# Here we declare an infinite loop, inside which
# we run a 1-second wait command (sleep 1) and
# a command that prints the * character to the screen
# without a newline (echo).
while sleep 1; do echo -n "*" >&2; done
}
# Before running the long command we call the function
# declared above in background mode (the & sign)
timer_func &
# And right after that we get the PID of the process we
# started by calling the timer_func function. We'll need it
# later to terminate this process.
timer_func_pid=$!
<Your long-running code or call to a long command goes here>
# At this point in the script, the long command has already
# finished, and we can stop drawing the asterisks. To do this,
# we kill the process by the PID we obtained above.
kill $timer_func_pid
An obvious shortcoming of this code is that if the user presses Ctrl+C - i.e. aborts the script's execution early - the timer_func function's process won't be terminated! And the asterisks will keep being drawn!
Comments