1

The following will read from an external file and output the data:

#!/bin/bash

while IFS='|' read hostname nickname; do

echo $hostname $nickname

done < "list.dat"

Where the list.dat file is:

firstserver|joe
secondserver|henry
thirdserver|jack

But I'd like to actually store the list.dat in the script itself (not externally) but don't know how to reference it as a variable/array and read from it with the same results...

3 Answers 3

6

Try using a here document:

#!/bin/bash
while IFS='|' read hostname nickname; do
echo $hostname $nickname
done <<LIMIT
firstserver|joe
secondserver|henry
thirdserver|jack
LIMIT
Sign up to request clarification or add additional context in comments.

2 Comments

Of course, if your values don't need to contain whitespace, it makes a lot more sense to use whitespace as the delimiter. Then you don't need to muck with IFS at all.
Your solution also works, thanks for the suggestion, I didn't know about 'here-document'
2

Here strings pass a variable or string as I think you want:

#!/bin/bash
input="firstserver|joe
secondserver|henry
thirdserver|jack"

while IFS='|' read hostname nickname; do

echo $hostname $nickname

done <<< "$input"

4 Comments

This seems to work but not with the space after input and the =
Fixed, thanks for pointing it out. Quoting $input is also a good idea.
Keep in mind, there is a bug in bash prior to 4.3 that could cause problems with combining a local IFS setting with a here string. Using a here document may be safer.
bash does not apply word-splitting or path expansion to a parameter expanded as a here string, so the quotes are unnecessary.
2

If bash 4 is available to you, I'd use an associative array:

declare -A servers=(
    ["firstserver"]=joe
    ["secondserver"]=henry
    …
)

for hostname in "${!servers[@]}"; do
    echo "$hostname" "${servers[$hostname]}"
done

This assumes the hostnames are unique.

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.