Curly braces on the command line

Curly braces on the command line

You can do some really interesting and time saving things using curly braces on the bash command line. Essentially, curly braces with a list of things separated by commas means run this command once for each item in the list.

This is best illustrated by a number of examples.

Create a complex folder hierarchy

mkdir -p folder/{1, 2, 3}/{a, b, c}

This creates this folder hierarchy:

folder/
1/
a/
b/
2/
a/
b/
3/
a/
b/

Rename files in a hierarchy

This renames foo/bar/baz/1 to foo/bar/baz/2

mv foo/bar/baz/{1,2} 

Rename variation

This renames /foo/bar/baz/1 to foo/bar/tweedle/2

mv foo/bar/{baz/1, tweedle/2} 

Shortcut for adding extensions

This renames file to file1.backup

mv file1{.,backup}

Add extensions with wildcard matching

This will find files containing the word “banana” and slap an extension on them. This is an interesting case in that {,.bak} means add an extension.

find . -name "banana*" -exec mv \{\}{,.bak} \; 

List files with multiple extensions

This lists all files with txt and doc extensions. Note that wildcards can only be outside the curly braces.

ls *.{txt,doc}