About nixCraft

Topics

Shell scripting and brace expansion

Posted by Vivek Gite [Last updated: December 18, 2005]

Expansion is performed on the command line after it has been split into words. Brace expansion is a mechanism by which arbitrary strings may be generated. A sequence expression takes the form {x..y}, where x and y are either integers or single characters. Simple bash brace expansion example:

$ echo F{1,2,3,4,5}
F1 F2 F3 F4 F5

It works with almost any command:

$ mkdir -p /home/project/{sales,purchase,reports}

It is funny but some time you can stuck in shell scripting very badly and you do not understand what is going on ... For example I need to expand hostnames using host1.my.com,host2.my.com,...host10.my.com then I can use brace expansion at shell prompt as follows:

$ echo host{1..5}.my.com
host1.my.com host2.my.com host3.my.com host4.my.com host5.my.com

Now try it in a shell script:

#!/bin/bash
HOSTS="$1"
for i in $HOSTS
do
ping $i
# rest of logic
done

And then executed script by typing command:

$ ./myscript host{1..5}.my.com 

It will not expand to host1.my.com, host2.my.com..... :/? It took me more than two hours, finally while chatting with my friend he told me to replace HOSTS="$1" with HOSTS="$@". Bingo it worked!
According to bash man page,"A sequence expression takes the form {x..y}, where x and y are either integers or single characters. When integers are supplied, the expression expands to each number between x and y, inclusive. When characters are supplied, the expression expands to each character lexicographically between x and y, inclusive. Note that both x and y must be of the same type". $@ is a special shell variable which. expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. I must admit I need to master shell shell scripting skills ;)

E-mail this to a friend      Printable version

You may also be interested in other helpful articles:

Discussion on This Article:

  1. riscphree Says:

    albeit simple, thats pretty sweet. I didnt know how to do that :D

Leave a Reply

We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Copyright © 2004-2008 nixCraft. All rights reserved - TOS/Disclaimer - Privacy policy - Sitemap - Powered by Open source software.