Reputation: 75
I have a file containing couple of words like :
server1 location1
server2 location2
I need to pass these in a while loop.
How do we assign them to two separate variables? Something like this may be
while read server,location
do
echo $server is in $location
done <file
I'm able to work with 1 variable very fine, but couldn't figure out this one.
Any help would be appreciated.
Upvotes: 1
Views: 4648
Reputation: 87054
I'm a bit rusty with shell scripting so I doubt that this is the best way, but you can do it like this:
set $(cat file)
while [ $# -gt 0 ]
do
echo $1 is in $2
shift 2
done
Another way is to use awk
:
awk '{for (i=1; i<NF; i+=2) printf "%s is in %s\n", $i, $(i+1);}' file
Upvotes: 1
Reputation: 121347
You need to use space between variables, not comma:
while read -r server location
do
echo "${server}" is in "${location}"
done <file
Note that first word will be read into server
and "everything else" will go into location
. So if your file happens to contain more than two words then you may want to ignore the rest with a dummy variable:
while read -r server location dummy
do
echo "${server}" is in "${location}"
done <file
Upvotes: 1