aboutsummaryrefslogtreecommitdiff
path: root/bin/untill
blob: 9980c813537a9ae16881597acdcd88ed0bc0679c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/bin/sh
set -eu

usage() {
	cat <<-'EOF'
		Usage:
		  until [-m MAX] [-n SECONDS] COMMAND...
		  until -h
	EOF
}

help() {
	cat <<-'EOF'


		Options:
		  -n SECONDS    the amount of seconds to sleep between
				attempts (default: 5)
		  -m MAX        the maximum number of attempts (default: unlimited)
		  -h, --help    show this message

		  COMMAND       the shell command to be executed


		Runs COMMAND until it eventually succeeds, trying atmost MAX
		times.  Sleep SECONDS between attempts.


		Examples:

		  Try flaky build until it succeeds:

		    $ until guix home build home.scm


		  Try atmost 10 timex to build until a new version is successfull,
		  waiting 30 seconds between attempts:

		    $ until -m 10 -n 30 -- x git pull AND make
	EOF
}


for flag in "$@"; do
	case "$flag" in
		--)
			break
			;;
		--help)
			usage
			help
			exit
			;;
		*)
			;;
	esac
done

_SECONDS=5
while getopts 'm:n:h' flag; do
	case "$flag" in
		m)
			MAX="$OPTARG"
			;;
		n)
			_SECONDS="$OPTARG"
			;;
		h)
			usage
			help
			exit
			;;
		*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))


ATTEMPT=1
while true; do
	printf 'Attempt %s.\n' "$ATTEMPT" >&2
	ATTEMPT=$((ATTEMPT + 1))
	if "$@"; then
		break
	fi
	if [ -n "${MAX:-}" ] && [ "$ATTEMPT" -gt "$MAX" ]; then
		printf 'Maximum number of attempts reached: %s.\n' "$MAX" >&2
		exit 1
	fi
	sleep "$_SECONDS"
done