In a Linux shell script I would like to use the timeout command to end another command if some time limit is reached. In general:
timeout -s SIGTERM 100 command
But I also want that my shell script exits when the command is failing for some reason. If the command is failing early enough, the time limit will not be reached, and timeout will exit with exit code 0. Thus the error cannot be trapped with trap or set -e, as least I have tried it and it did not work. How can I achieve what I want to do?
In Linux, an exit code indicates the response from the command or a script after execution. It ranges from 0 to 255. The exit codes help us determine whether a process ran: Successfully.
In Linux operating system, the “timeout” command is a command-line utility that is used to terminate a running process after a set period. It is used for the processes that run continuously. Moreover, the exit status of running processes can also be accessed using the “timeout” command.
The syntax for the timeout command is as follows: timeout [OPTIONS] DURATION COMMAND [ARG]… The DURATION can be a positive integer or a floating-point number, followed by an optional unit suffix: s - seconds (default)
When a script that has been executed from the command line ends, a number is displayed in the command prompt window. This number is an exit code. If the script ends unexpectedly, this exit code can help you find the cause of the error.
Your situation isn't very clear because you haven't included your code in the post.
timeout
does exit with the exit code of the command if it finishes before the timeout value.
For example:
timeout 5 ls -l non_existent_file
# outputs ERROR: ls: cannot access non_existent_file: No such file or directory
echo $?
# outputs 2 (which is the exit code of ls)
From man timeout
:
If the command times out, and --preserve-status is not set, then exit with status 124. Otherwise, exit with the status of COMMAND. If no signal is specified, send the TERM signal upon timeout. The TERM signal kills any process that does not block or catch that signal. It may be necessary to use the KILL (9) signal, since this signal cannot be caught, in which case the exit status is 128+9 rather than 124.
See BashFAQ105 to understand the pitfalls of set -e
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With