This is possible with the build-in command
timeout. Linux has a command-line utility called a timeout, which enables you to execute a command with a time limit.
The syntax is as follows.
timeout [OPTION] DURATION COMMAND [ARG]...
An example is using a timeout for the with the ping command:
timeout 5 X.X.X.X
You can also use other options like minutes, hours and so on. It is also recommended to use the --kill-after option as sometimes the commands may continue to run even after timeout sends the initial signal.
timeout --kill-after=5 2s ping X.X.X.X
The –preserve-status option allows timeout to exit with the same status as COMMAND, even when the command times out.
timeout –preserve-status 10s ping X.X.X.X
The –foreground option when not running timeout directly from a shell prompt, allow COMMAND to read from the TTY and get TTY signals; in this mode, children of COMMAND will not be timed out:
For example you can ssh to a remote server and execute the top/htop command and then when the timeout is reached you will get back to the foreground:
timeout --foreground 30s ssh -t user@server htop
timeout --foreground 30s ssh -t user@server top
The timeout command is a simple way to let a command run for a given amount of time.
Hope this briefly explains the usage and the advantage of the timeout command.