Brace expansion

From LQWiki
Jump to navigation Jump to search

Brace expansion is a facility in the bash shell which allows a list of strings to be expanded with a common prefix or suffix. The string list must be comma-separated and enclosed within braces. If a prefix is used, it goes directly before the opening brace. A suffix goes directly after the closing brace.

Brace expansion is often a quick way to get things done in the shell. For example, suppose that you wish to rename a file in a remote directory to which you have write access. You cannot do it with:

  1. mv /path/to/file/name1 name2 because that would move the file into the current working directory with the name name2 rather than renaming it in situ.
  2. mv /path/to/file/name1 /path/to/file/name2 would work but involves a lot of typing.
  3. mv /path/to/file/{name1,name2} expands to option 2 while involving hardly more keystrokes than option 1.

Null strings are permissible. For example, the command mkdir -p dir1/{,dir2/}dir3 will expand to mkdir -p dir1/dir3 dir1/dir2/dir3. This will create a directory dir1 containing two subdirectories called dir2 and dir3. dir2 will also contain a separate subdirectory called dir3.