1

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.

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

9 Comments

Are you able to parse the whole file using read without dropping the rest of the line? I think that's what the OP is after.
I have edited the post to make it clear (you can see from the edit history for what OP meant to ask). It did look like what you are saying. But it's a due to poor formatting in the question. Sorry!
I might be missing something, but I don't see that in the edit history. I see that you have edited the question not the OP???
@mhawke All I did was format those two lines OP had. You have to see the source of the history, not just history before accusing me of edting it to suit my answer.
@mhawke Here's the link for you: source. If you still don't believe, flag it to a moderator.
|
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.