RetroCode UK

Published Date Mar 14, 2017 Reading Time ~2 minutes RSS Feed Linux Command Line

Linux Command Prompt Tips

It’s easy to use the command line effectively, and not even be aware of some of the myriad options available, but it’s worth keeping an eye out for anything that could make life easier. In this entry I’ll be looking at a few commands that have been useful time-savers to be lately.

Brace Expansion

Firstly, is something called brace expansion. The simplest way of explaining this is with an example. Take the following command:

touch file_{a,b,c}.txt

This is exactly the same as typing:

touch file_a.txt file_b.txt file_c.txt

A more useful example, to create a back-up of a file is: cp README.md{,.backup} which will expand to cp README.md README.md.backup before executing.

In bash, it’s also possible to use ranges with {1..10}, so for example, you could create ten directories with the command mkdir images_{1..10}.

Note: If you’re using fish shell then brace expansion will work fine, but the syntax for ranges is slightly different. The equivalent would be (seq 10). You can try this simply with echo images_(seq 10)

Globstar

Using double asterisks in path names can be really useful. I first came across it when using gulp which uses the convention (adopted in bash 4) to expand sub-directories.

One simple example I sometimes use is ll **/*.py | grep part_of_filename which will search all subfolders for any file with a matching part. The downside to this is it doesn’t look in the current folder, so you can extend it by using ll **{,/*}.py which also will list those files.

Summary

There are many surprising ways to use these techniques, but obviously they only work if the command accepts multiple file options. I also recommend trying them with echo first to get a feel for what expansions are possible, and for what kind of results you might get.