Brace expansion in bash and zsh

Bash and zsh both have a very neat feature for expanding a single word into more: brace expansion.
For the simplest example, imagine you need to move file.old as file.new. Normally you type:

$ mv file.old file.new

Brace expansion can save you a little bit of typing:

$ mv file.{old,new}

The command actually executed will be identical to the previous one, “file.{old,new}” gets converted into “file.old file.new”.

You can also provide a number range inside the brace:

% echo test{1..13}
test1 test2 test3 test4 test5 test6 test7 test8 test9 test10 test11 test12 test13

With a third parameter, the number will be increased by that much each time (step):

% echo test{1..13..2}
test1 test3 test5 test7 test9 test11 test13

Only a zsh feature is padding. You can add leading zeros to generated number to make them all the same (character) size, by adding zero(s) to the third parameter:

 % echo test{1..100..010} 
test001 test011 test021 test031 test041 test051 test061 test071 test081 test091

Zsh offers even more flexibility after setting BRACE_CCL option – you can use range of characters as well:

% setopt BRACE_CCL
% echo test{a-d} 
testa testb testc testd
  1. Hi Tomek!

    Braces are sweet. You can also leave the first brace argument out if you just want to append something to the filename. I find myself doing this sometimes when making a quick and dirty backup of a file: cp foo.txt{,~}.

    I had no idea you could specify an interval for a number range. That’s cool :)

    Are you using zsh a lot these days? noting a few blog entries… worth a look?

Leave a Comment


*


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">