(One)-minute geek news

Group talks, Laboratoire de Chimie, ENS de Lyon

Brace expansion


Multiple expansions are featured in Bash. One of the most basic yet powerful is brace expansion.

Basic usage

Words containing a brace expansion are expanded into a list of words where the brace expansion was replaced with each of the comma separated elements within the brace expansion.

In this specific case, I will not try to explain more this feature which is pretty hard to explain but easy to understand from examples. So let us start!

List of strings

  • mv file_{new,old} is equivalent to mv file_new file_old
  • cp file{,_backup}_data is equivalent to cp file_data file_backup_data
  • mkdir md_{C2H2,C2H4,H2O,CO}_Pt111_CP2K is equivalent to mkdir md_C2H2_Pt111_CP2K md_C2H4_Pt111_CP2K md_H2O_Pt111_CP2K md_CO_Pt111_CP2K

Beware that brace expansion is not performed in a quoted string: touch file_{a,e} "data_{a,e}" is equivalent to touch file_a file_e "data_{a,e}".

Beware also about unescaped spaces in your words touch file {a,e} "file "{a,e} is equivalent to touch file a e file_a file_e.

Ranges

  • mkdir dir{3..5} is equivalent to mkdir dir3 dir4 dir5
  • mkdir cutoff_{100..200..50} is equivalent to mkdir cutoff_100 cutoff_150 cutoff_200
  • mkdir test{b..f} is equivalent to mkdir testb testc testd teste testf

Advanced usage

Multiple brace expansions can be applied to a same word: mkdir md_{CO,H2O}_{top,fcc} is equivalent to mkdir md_CO_top md_CO_fcc md_H2O_top md_H2O_fcc.

Brace expansions can be nested: mkdir dir{a,b,{1..3}} is equivalent to mkdir dira dirb dir1 dir2 dir3.

Parameters expansion are compatible with brace expansion: touch {$HOME,~rstaub,$(pwd)}/data is equivalent to touch /home/rstaub/data ~rstaub/data ./data.

References

man bash