Shell scripting: watch command alternative via while loop
We may frequently find ourselves in situations where we want to run a command periodically to view its progress. A watch command is an amazing tool meant to be used for this exact purpose. Please read our article on the Linux watch command to know more about it. In this article, we’ll explain how you may use the while loop in a bash shell to simulate the functionality provided by the watch command. The syntax is simple as shown below: while true; do echo "Running <command> at $(date)"; <command>; sleep <interval in sec> ; done Explanation of the above shell script The true keyword turns the while loop into an infinite loop since the exit status or condition to be checked by the while loop will always literally be true. This is followed by the “; operator” which is useful to concatenating/chaining commands in Linux/Unix. Next, we display the name of the command we’ll be executing and $(date) performs a command substitution for the date command. This is followed by the actual command to be executed. Finally, we have the Linux sleep command where we specify the time in seconds after which the next iteration of the while loop should run and display the output of the command. The done statement closes the while loop. You may terminate the while loop by pressing ctrl+c. Example: We’ll now demonstrate a simple...
Read More