A common, and often overlooked, need for scripting is addressing hanging, or unresponsive commands. What should your script do if one of it's ste
ps takes much, much, much longer than expected? A hanging, or unresponsive, subprocess will result in a hanging job which in turn can prevent oth
er jobs from running. Let's spend a bit of time how to address such an need.
The 'timeout' command is provided by the coreutils package, often readily available on default installation for most distributions.
$ sleep 10
$ echo $?
0
Execution of subprocesses generally set a return code, zero or non-zero, often zero indicating successful execution of the command, non-zero return codes if it failed for some reason. The above command sequence will execute a sleep command (for 10 seconds), the second command echoing the return code. Assignment of $? to zero indicates the sleep command executed successfully.
So, what if we wanted to prevent a hanging command to go undetected and/or prevent the rest of a script from running. Let's say we want to enforce a command takes no longer than 5 seconds.
$ timeout 5 sleep 10
$ echo $?
124
After 5 seconds, the command terminates, the return code 124 indicates the command timed out. Usage of this allows setting hard constraints on how long a command is allowed to run before terminating or being terminated. The return code allows determining if the command timed-out.
Cheers.
Personal software engineering blog where I share a variety of topics that interest me.
Sunday, April 12, 2026
Detect Command Timeouts using Bash
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment