-
-
Save cwedgwood/1287ced2a67c44607cefdacd082f4ad8 to your computer and use it in GitHub Desktop.
test of running [ba]sh command with a timeout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
#set -x | |
evcount=0 | |
function eventually() { | |
if [ $evcount -gt 5 ] ; then | |
return 0 | |
fi | |
evcount=$(($evcount + 1)) | |
return 1 | |
} | |
# run a command until it returns success or we timeout | |
function timeout_run() { | |
timeout=$1 | |
shift | |
pause=$1 | |
shift | |
elapsed=0 | |
while : ; do | |
echo "XXX running command time=$timeout pause=$pause elapsed=$elapsed cmd: $@" | |
if $@ ; then | |
return | |
fi | |
if [ $elapsed -ge $timeout ] ; then | |
break | |
fi | |
sleep $pause | |
elapsed=$(($elapsed + $pause)) | |
done | |
echo "XXX giving up..." | |
exit 1 | |
} | |
evcount=0 | |
function eventually() { | |
if [ $evcount -gt 5 ] ; then | |
return 0 | |
fi | |
evcount=$(($evcount + 1)) | |
return 1 | |
} | |
# test/demo | |
# has to be robust to -e | |
set -e | |
# works | |
timeout_run 10 1 sleep 1 | |
# works | |
timeout_run 10 1 true | |
# works | |
timeout_run 10 1 curl -v https://f00f.org > /dev/null | |
# works, eventually | |
timeout_run 20 2 eventually | |
# will fail | |
timeout_run 10 1 false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment