Bash trick: Repeat last command until success

Marko Lukša
Jun 20 · 2 min read

Sometimes you run a shell command and it fails because you ran it too soon. But if you re-run it a few times, it eventually succeeds.

One example of this is trying to stream the logs of a Kubernetes pod immediately after creating it:

$ kubectl logs mypod -f
Error from server (BadRequest): container "main" in pod "mypod" is waiting to start: ContainerCreating
$

Ideally, kubectl would wait for the container to actually start up and then start streaming its logs (as reported in issue 28746), but it doesn’t. Thus, you need to repeatedly hit the up-arrow and re-execute the command until it succeeds.

Is there a way to automate this? Of course there is.

The solution

The solution is very simple. Just add the following function to your .bashrc file:

rpt() {
CMD=$(fc -ln | tail -2 | head -1)
echo "repeating until success: $CMD"
until $CMD
do
sleep 1
done
}

Now, if kubectl logs -f fails, you can simply type rptand it will re-run the kubectl command until the container starts and the logs can be streamed:

$ kubectl logs mypod -f
Error from server (BadRequest): container "main" in pod "mypod" is waiting to start: ContainerCreating
$ rpt
repeating until success: kubectl logs mypod -f
Error from server (BadRequest): container "main" in pod "mypod" is waiting to start: ContainerCreating
Error from server (BadRequest): container "main" in pod "mypod" is waiting to start: ContainerCreating
Error from server (BadRequest): container "main" in pod "mypod" is waiting to start: ContainerCreating
Error from server (BadRequest): container "main" in pod "mypod" is waiting to start: ContainerCreating
2019-06-19T14:32:54.007Z INFO mypod is starting up...
...

Of course, this also works with other commands:

Marko Lukša

Written by

Software engineer at Red Hat. Author of Kubernetes in Action - http://bit.do/kubia