Brace Expansion - Generate Command Line Strings | Online Free DevTools by Hexmos

Master brace expansion to generate command line strings with ranges and lists. Learn examples for creating files, directories, and backups efficiently.

Brace Expansion

What is Brace Expansion?

Brace expansion is a powerful feature in shell environments like Bash that allows for the generation of a range of strings to be used on the command line. It's incredibly useful for creating lists of sequential data or for running any command on a sequence of data without manually typing each item.

A range or a comma-separated list of data can be used for expansion. These lists are enclosed within curly braces {}.

  • {0..4} generates a sequence from 0 to 4 (i.e., 0 1 2 3 4).
  • {alice, bob, charlie} generates the strings alice, bob, and charlie.

The expansion can also be modified with an optional string, known as a preamble or prefix, which is added to the beginning of each generated string. Similarly, a postfix or postscript can be appended to each string.

The general syntax for brace expansion includes:

  • String list: {String1, String2, ...}
  • Range list: {start..end}
  • Range list with custom increment: {start..end..increment}
  • With prefix and postfix: <prefix>{ string or range }<postfix>

Brace Expansion Examples

Here are several practical examples demonstrating the utility of brace expansion:

  • Create files for each day of the month:
    touch {1..31} - This command creates 31 empty files named 1 through 31.
  • Print even numbers within a range:
    echo {2..100..2} - This will output all even numbers from 2 to 100.
  • Create multiple directories at once:
    mkdir /some/path/{input, output, backup, error} - This creates four directories: input, output, backup, and error, within the specified path.
  • Print alphabets in reverse order:
    echo {z..a} - This command outputs the lowercase alphabet from z to a.
  • Create a backup of a file:
    cp file.txt{,.bkp} - This is a concise way to copy file.txt to file.txt.bkp. The empty string before the comma expands to nothing, and the string after expands to .bkp.
  • Restore from a backup file:
    mv file.txt{.bkp,} - This command renames file.txt.bkp back to file.txt.
  • Create nested folders for monthly logs:
    mkdir -p ~/logs/{January/{1..31},February/{1..28},March/{1..31}} - This command creates a directory structure for logs, with subdirectories for each day of January, February, and March. The -p flag ensures that parent directories are created if they don't exist.

Brace expansion significantly simplifies complex command-line operations, making scripting and system administration more efficient.

For further reading on shell expansions, refer to the Bash Manual on Shell Expansion.