Search code examples
bashcommand-line-argumentssquare-bracket

How to expand an argument with a range in square brackets in a bash script?


I want to use strings containing numbers as input to my script. This list can be rather long and may contain consecutive ranges of numbers, so I thought about doing ls style list specification. However, how can I expand this list in my script? To be more specific, I want to run:

myscript node-[2,5-7,10-13]

and be able to loop through node-2, node-5, node-6, etc. in my script.

Update: It seems that I need to use curly brackets and dots for lists. I can convert the string to that, but how do I make the script treat it as a list then? What I can do:

nodelist=`echo $1 | sed 's/\[/\{/' | sed 's/\]/\}/' | sed 's/-/../'`

but for input node[1-3] for example I get:

>echo $nodelist
node{1..3}

Solution

  • Do you mean something like this?

    $ echo node-{2,{5..7},{10..13}}

    node-2 node-5 node-6 node-7 node-10 node-11 node-12 node-13

    Edit

    You could reformat your ranges to be bash-friendly:

    echo '[2,5-7,10-13]'|sed -e 's:[[](.*)[]]:{\1}:' -e 's:([0-9]+)[-]([0-9]+):{\1..\2}:g'

    {2,{5..7},{10..13}}