Skip to content

Instantly share code, notes, and snippets.

@jcbf
Created July 17, 2020 14:27
Show Gist options
  • Save jcbf/56ce19814ebd3f76cb0fde466d8581fe to your computer and use it in GitHub Desktop.
Save jcbf/56ce19814ebd3f76cb0fde466d8581fe to your computer and use it in GitHub Desktop.
bash timeout
./run.sh 10 slow_command
./run.sh 3 sleep 5
#!/bin/bash
# run
# Run command with timeout $1 seconds.
# Timeout seconds
timeout_seconds="$1"
shift
# PID
pid=$$
# Start timeout
(
sleep "$timeout_seconds"
echo "Timed out after $timeout_seconds seconds"
kill -- -$pid &>/dev/null
) &
timeout_pid=$!
# Run
"$@"
# Stop timeout
kill $timeout_pid &>/dev/null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment