[prog] assigning variables in sh

Almut Behrens almut-behrens at gmx.net
Wed Jan 12 05:58:46 EST 2005


On Tue, Jan 11, 2005 at 09:54:09AM +0000, Conor Daly wrote:
> On Mon, Jan 10, 2005 at 01:38:58PM -0500 or thereabouts, aec wrote:
>  
> > I want to now, perform an action on each server in the list, so
> > I need to iterate over the list somehow and this where I not sure 
> > what the best approach is.
> 
> My method of iterating a list (generally in a file) goes like this:
> 
> (...snipped lots of good stuff...)


I agree with everything Conor said[1] ... but if $servers always just
contains a whitespace seperated list of server names, and the list
isn't excessively long (something up to a few thousand entries should
be fine), you could also simply do the following (not requiring any
intermediate temporary files):

  servers=`curl -q "http://list.somelist.foo/db/?action=LIST&nameport=&" 2>/dev/null | grep 0023 | cut -f1 -d ' '`
  [ $? != 0 ] && echo " NOT okay" && echo "ERROR: unable to curl http:////list.somelist.foo" && exit 1
  echo " okay"
  
  for serv in $servers; do
    # do something with $serv ...
    echo $serv
  done


Or, if, for whatever reason, you'd find it more convenient to hold the
servers in variables explicitly named server1, server2, ..., serverN,
you could do

  n=1
  for serv in $servers; do
    eval server$n=$serv
    let "n = $n + 1"
  done

  # check what "serverN" variables we've set
  set | grep '^server[0-9]'

This would print something like:

server1=141.414.184.125:5156
server2=237.215.575.155:5157
server3=136.315.470.145:6000
server4=xion.serve.org:5154
server5=remaag.lidet.net:5555
server6=showme.bomang.ca:25154
server7=noel.sleepy.us:5165

In bash you could also use the more compact notation:

  n=1
  for serv in $servers; do
    eval server$((n++))=$serv
  done

though, personally, I'd consider this approach less easy to handle than
to directly iterate over the list of values, as shown first...

Cheers,
Almut


[1] well, almost :)  There are two minor typos in the code:
"read $LINE" should be "read LINE", and there should be whitepace
around the test brackets, i.e. "while [ $LINE ]; do", not "[$LINE]".



More information about the Programming mailing list