Want some programming help? [close]

Bash Brace Expansion Tutorial

Introduction

Bash brace expansion is an incredibly valuable feature once you commit it to memory and begin using it on a regular basis. It will save you immense amounts of typing. This also works in Zsh.

How it works

When you provides a set of braces {} with comma-separated values inside, Bash will expand each one into a separate argument.

The simple example to demonstrate this is using echo like this:

echo Hello {Jack,Jill,Bill}
# Outputs: Hello Jack Jill Bill

echo Hello Ja{ke,net,cob,red}
# Outputs: Hello Jake Janet Jacob Jared

echo Hello S{u,uzann,uzi}e
# Outputs: Hello Sue Suzanne Suzie

echo Hello {J,K,T}immy
# Outputs: Hello Jimmy Kimmy Timmy

The brace expansion will take the current word that the braces are in, and expand it to create a unique word for each value inside the braces.

You can also have it auto increment numbers and characters. For example

echo {1..10}
# Outputs: 1 2 3 4 5 6 7 8 9 10

echo {1..10..2}  # Increment by 2 each time
# Outputs: 1 3 5 7 9

echo {a..e}
# Outputs: a b c d e

echo {a..z..2}  # a through z incrementing by 2 each time
# Outputs: a c e g i k m o q s u w y

echo {A..z..2}  # Capital letters come before lowercase in ASCII
# Outputs: A C E G I K M O Q S U W Y [ ] _ a c e g i k m o q s u w y

Practical examples

Here are a few practical examples of how I use brace expansion regularly.

Changing a file extension

# Change a .txt to a .md
mv myfile.{txt,md}

Rename directory for backup

# Add .backup to a directory name
mv /my/directory{,.backup}

Installing similarly named packages

# Installs Java JRE + JDK + JavaFX on Fedora
sudo yum install java-1.8.0-openjdk{,-devel,-openjfx}

# Install multiple PHP packages on Ubuntu
sudo apt install php-{common,mbstring,mysql}

Make several directories at once

mkdir -p $HOME/my_new_project/{src,docs,build}

Conclusion

You should have a basic understanding of how Bash brace expansion works and how you can apply it to some common tasks. What other kind of uses can you think of?

References

Advertisement