Site icon Leonid Mamchenkov

Bash trick: Repeat last command until success

More and more often I come across a scenario where I need to repeat the shell command until it succeeds. Here are a couple of examples:

Sure, I can always press the up arrow key and Enter, to repeat the last command from the history. But it is a tiny bit annoying.

Today I came across this little trick, that solves the problem. Add the following function to your .bashrc:

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

Now you can run “rpt” to repeat the latest command until it succeeds.

Handy!

Exit mobile version