Archives

Tags

Bash shells, curly braces, substitutions, attack!

Here is something I do all the time:

$ cp a-file-that-is-badass a-file-that-is-badass.old
...
$ cp a-file-that-is-badass.old a-file-that-is-badass

But, considering I'm a wannabe hacker, I knew there was going to be a much faster way of achieving the same thing. Enter the curly brace of doom!

Let me slip on my hack suit and try that again:

$ cp a-file-that-is-badass{,-old}
$ cp a-file-that-is-badass{-old,}

Here, we are utilising a feature in bash called brace expansion. Basically, it is telling the shell to prepend the contents of the command to the left of the first brace to each string inside the comma-delimited list within the braces. Anything remaining to the right of the braces is appending to each expanded string.

Brace expansion can take place anywhere inside your command. You can even nest them!

Another example (in the case of a collegue with horrible spelling):

$ mv lib/complex/{fisicks,physics}.py

The possibilities are endless...