Using Expansions Commands in the Linux Terminal - Part 2


Using Expansions Commands in the Linux Terminal - Part 2

This week we are checking out more expansion commands with nesting and parameters.

Last week we started checking out expansions- what they mean, how they work, and how the shell sees and executes them. This week I wanted to touch on a few extra expansion commands you can use and experiment with. This week we're checking out brace expansion. Bracing can make several text strings out of one pattern, with braces around them.

Try echo Front-{A, B, C}-Back. You can also do examples like: echo Number_{1..5} or echo {Z..A}, and nest expansions by doing something like echo a{A{1,2},B{3,4}}b. This can be useful if you need to make lists of files, say if you had a large collection of photos that you need to list, or if you need a list of Directories: if you had a bunch of photos in directories called 2009-1 through 2011-12, you could list those directories by typing mkdir {2009..2011}-0{1..9} {2009..2011}-{10..12} then type ls.

You can expand parameters, but this is usually more useful with shell scripts. For example, type echo $USER to show your username. Type printenv | less to show a list of available variables. Normally with expansion, if you mistype something while typing a command, you'll notice it echos the mistyped pattern. If you mistype a command while doing parameter expansion, it'll give you a blank string.

The output of a command can also be used as an expansion, like this: echo $(ls). ls -l $(which cp) will show us the results of which cp as an argument to the ls command. This'll let us see the cp program without the pathname being known. Here's an example of using pipelines with expansions: file $(ls /usr/bin/* | grep zip). The pipeline became the argument list of the file command. And if you really feel like showing off you can use the old school technique that looks like: ls -l `which cp`.

Now that you know so much about expansion and how it's used, you can see how this will be very useful once you get more advanced with the terminal. Make sure to email me with your thoughts. And be sure to check out our sister show, Hak5 for more great stuff just like this. I'll be there, reminding you to trust your technolust.