Skip to content

Instantly share code, notes, and snippets.

@mogproject
Created July 24, 2021 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mogproject/3379b9af7b704a5b85042382f963e93f to your computer and use it in GitHub Desktop.
Save mogproject/3379b9af7b704a5b85042382f963e93f to your computer and use it in GitHub Desktop.
Example of running a command with time limit but not affecting the errexit option in bash.
#!/bin/bash
TIMEOUT=timeout
run_with_timeout() {
oldopt=$-
set +e
$TIMEOUT $@
ret=$?
if [[ $ret -eq 124 ]]; then
ret=0
fi
set -$oldopt
return $ret
}
set -e
run_with_timeout 1s true
echo "Success within time limit: rc=$?"
run_with_timeout 1s sleep 10
echo "Timeout: rc=$?"
run_with_timeout 1s false
echo "*THIS SHOULD NOT BE PRINTED* Failure within time limit: rc=$?"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment