Dan
Dan

Reputation: 951

Reference data internally in Bash script

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...

Upvotes: 1

Views: 87

Answers (3)

Politank-Z
Politank-Z

Reputation: 3729

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"

Upvotes: 2

Ram&#243;n Gil Moreno
Ram&#243;n Gil Moreno

Reputation: 829

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

Upvotes: 6

kojiro
kojiro

Reputation: 77157

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.

Upvotes: 2

Related Questions