Linux command DRY

Bash can sometimes stun you, so let me teach you a little trick to make your life easier. And that is to Don’t Repeat Yourself (DRY for short).

You probably use Linux for your day to day tasks, and most of the time, you have to deal with a lot of repeating commands, sometimes, painfully long commands that you have to repeat again and again, just think about this example:

cp /var/log/apache2/error_log.20151210.gz /var/log/apache2/error_log.20151211.gz /var/log/apache2/error_log.20151214.gz /var/log/apache2/error_log.20151215.gz .

In this scenario, the user is probably trying to copy those files to his current directory. What if you want to add more other similarly named files, how do you do this, type it by hands? Even with the help of the tab completion, it will still be a pain in the fingers. Then why make it unnecessarily harder for us?

Enter Brace Expansion.

Do you know you can save yourself and other people the time and effort? By typing it this way instead

cp /var/log/apache2/error_log.2015121{0,1,4,5}.gz .

How exhilarating was that?linux command dry article

Ok, you want to do things that way from now on, I understand. But how does it work?

It works by repeating the characters you typed that are connected directly to the braces (space will break it), and the character or characters you typed inside the braces separated by commas are each placed on that part as it gets repeated. So in this case

echo Hi{you,me,them}

will output

Hiyou Hime Hithem

You can also use ranges

echo {1..5}num
1num 2num 3num 4num 5num
echo Letter{X..Z}
LetterX LetterY LetterZ
echo {9..6}reverse
9reverse 8reverse 7reverse 6reverse

If you need a space character, you should enclosed the characters including the space with quotes

echo 'Hello '{World,Galaxy,Universe}
Hello World Hello Galaxy Hello Universe

So go on, experiment with it. May this new found information help you a lot.

Stay tuned for more of our helpful articles on this site.