[prog] assigning variables in sh

Conor Daly c.daly at met.ie
Tue Jan 11 20:54:09 EST 2005


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:

###############################
exec < $FILE

read $LINE

while [$LINE]; do
  server=`echo $LINE | cut -f1 -d:`
  port=`echo $LINE | cut -f2 -d:`

# do stuff with $server

  read $LINE
done
###############################
 
> I would love to end up with a set of variables, $server1 $server2 
> and so on.. this would make further operations later on in the 
> script a cinch. 

You can generate arrays in bash (not sure about sh)
http://www.linuxvalley.it/encyclopedia/ldp/guide/abs/arrays.html

The following will read a file into an array but it will fall over on blank
lines in the file:

###############################
#!/bin/bash

declare -a TOKENS

exec < $FILE

read LINE
index=0
while [ $LINE ]; do
  TOKENS[$index]=$LINE
  let "index = $index + 1"
  read LINE
done

count=${#TOKENS[@]}

for i in `seq 0 $count`; do

  if [ $i -lt $count ]; then
    echo ${TOKENS[$i]}
  fi

done

echo "$count tokens"
###############################


If you have already constructed your list of servers in the form: $server1,
$server2..., you can loop over them thus:

###############################
for server in $server{1,2,3}; do
.. $server
done
###############################

 
Conor
-- 
Conor Daly,                   Please avoid sending me 
Met Eireann, Glasnevin Hill,  Word or PowerPoint attachments.
Dublin 9, Ireland             http://www.fsf.org/philosophy/no-word-attachments.html
Ph +3531 8064276 Fax +3531 8064247


**********************************************************************
This e-mail and any files transmitted with it are confidential 
and intended solely for the addressee. If you have received
this email in error please notify the sender.
This e-mail message has also been scanned for the
presence of computer viruses.
**********************************************************************



More information about the Programming mailing list