Skip to content

Instantly share code, notes, and snippets.

@nathants
Last active August 20, 2022 08:06
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 nathants/dc5d43c1e57b9bbb3a654491df93e4d6 to your computer and use it in GitHub Desktop.
Save nathants/dc5d43c1e57b9bbb3a654491df93e4d6 to your computer and use it in GitHub Desktop.
#!/bin/bash
# The MIT License (MIT)
# Copyright (c) 2022-present Nathan Todd-Stone
# https://en.wikipedia.org/wiki/MIT_License#License_terms
set -eou pipefail
# usage: auto-restart.sh python program.py
trap 'exit 1' SIGINT
count=$(ps -eo args | grep ^/bin/bash | grep "auto-restart $*"$ | grep -v grep | wc -l)
if (($count > 2)); then
echo already running: auto-restart $@ >&2
exit 1
fi
reset_count_after_seconds=${reset_count_after_seconds:-10}
max_retries=${max_retries:-5}
now() { date +%s; }
last=$(now)
retry_count=0
while true; do
if eval "$@"; then
echo exited 0: "$@" >&2
else
echo exited $?: "$@" >&2
fi
seconds_since_last_bounce=$(($(now) - $last))
if (($seconds_since_last_bounce > $reset_count_after_seconds)); then
echo resetting bounce count since $seconds_since_last_bounce seconds have passed since the last bounce >&2
retry_count=0
fi
retry_count=$(($retry_count + 1))
if (($retry_count > $max_retries)); then
echo exceeded max max_retries $max_retries
exit 1
fi
last=$(now)
echo sleep for retry_count=$retry_count seconds >&2
sleep $retry_count
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment