JKaan
JKaan

Reputation: 329

ZSH Custom function like repeat

I have a command which I want to repeat when a certain error occurs. To make this generic I would like to come up with a function that can take any other function to basically wrap that behaviour, very similar to repeat in ZSH.

So what I would like to have is something like this:

repeatWhenError { someFunction() }

This would repeat the function within the braces until it succeeds successfully. Is there an easy way to implement this in ZSH?

Upvotes: 1

Views: 91

Answers (1)

HappyFace
HappyFace

Reputation: 4093

From my dotfiles:

retry () {
    retry-limited 0 "$@"
}
retry-limited () {
    retry-limited-eval "$1" "$(gquote "${@:2}")"
}
retry-limited-eval () {
    local retry_sleep="${retry_sleep:-0.1}"
    local limit=0
    local ecode=0
    until {
            test "$1" -gt 0 && test $limit -ge "$1"
        } || {
            eval "${@:2}" && ecode=0
        }
    do
        ecode="$?"
        ecerr Tried eval "${@:2}" "..."
        sleep $retry_sleep
        limit=$((limit+1))
    done
    return "$ecode"
}
gquote () {
    \noglob : Use this to control quoting centrally.
    print -r -- "${(q+@)@}"
}
ecerr () {
    print -r -- "$@" >&2
}

Usage:

retry someFunction

Upvotes: 1

Related Questions