Preserving Command Line Loop Formatting in Bash

If you’re a heavy bash user you’ll often find yourself writing short snippets of code on the command line. Typically they’ll be based around a main loop and you’ll end up entering them over multiple lines to keep them readable. Unfortunately when you try reuse the command, by retrieving it from the bash command history, it’ll be transformed in to one semicolon laden unreadable mass. Unless you read on…

One of the options bash allows you to set is ‘lithist’. If you enable it, either for the current session, by entering 'shopt -s lithist' or by putting adding the command to your .bash_profile or .bashrc all future multi-line commands will be correctly preserved. You’ll go from this:

$ for file in `ls *`; do command $file; otherthing $file; done

To this:

$ for file in ls *
  command $file
  otherthing $file

Which as you can see is much easier to read. One note though, enabling this option means that commands are also stored with embedded newlines in the .bash_history file. While this isn’t necessarily a problem it does mean that grepping through that file may only return parts of a single command.