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:

  • Reboot a server. Try to remotely login to it via ssh. This fails until the server actually boots up. Keep trying until connected.
  • Start an application that writes to the log file. Run “tail -f some.log” to watch the log messages. This fails if the log file does not exist yet. Keep trying until the application creates the log file and writes something into it.

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!

40x speed up of ls on large dirs

If you ever tried listing a directory with a lot (10,000+) of files in it, I’m sure you know how annoyingly slow ‘ls’ can be. Turns out there is a simple way to make it better. Have a look at the “When setting an environment variable gives you a 40x speedup” blog post.

Or just do the following:

export LS_COLORS='ex=00:su=00:sg=00:ca=00:'

This will disable colors on the executable files, setuid/setgid bits, and capabilities.

The Book of Secret Knowledge

The Book of Secret Knowledge” is a collection of awesome lists, manuals, blogs, hacks, one-liners, cli/web tools and more.  It is intended for everyone and anyone – especially for System and Network Administrators, DevOps, Pentesters or Security Researchers.

While you are at it, also have a look at:

Bash parameter expansion

If you’ve ever written a bash script with variables, and know that it wasn’t your last one,  I promise you, you’ll love this wiki page.  It covers a whole lot of different ways to expand and manipulate variable values in bash, all on a single, conveniently organized page.

up – the Ultimate Plumber


The Ultimate Plumber, or up for short, is an excellent interactive tool for anyone who is building complex command sequences for processing text on the Linux command line.  If you are a frequent user of grep, sort, cut, awk, sed, and other similar commands, have a look at this demo.  I’m sure up will save a tonne of time once you get a hang of it.