linuxbashcentos7freeipa

bash - store multiple items from a file line into array and store each item in its own variable


I have a file with multiple lines in this format (reverse dns entries):

251.2.168.192.in-addr.arpa core.admin.my.lan.

I'm trying to break up the line into multiple variables so I can use them to recreate its IP address, and use as an IPA DNS entry line

( ipa dnsrecord-add admin.my.lan core --a-rec 192.168.2.251).

So far I have been able to come up with this:

while read line ; do 
    IFS=', ' read -r -a my_array <<< $(echo $line | awk -F '[. ]' '{print $4, $3, $2, $1, $7, $8}')
     while IFS= read -r first second third fourth fifth sixth; do 
        echo "first=$first second=$second third=$third fourth=$fourth fifth=$fifth sixth=$sixth"; 
        done <<< "$my_array" 
        unset my_array 
done <reverse_entries.txt

but this only creates the first variable $first:

first=192 second= third= fourth= fifth= sixth=
first=10 second= third= fourth= fifth= sixth=
first=192 second= third= fourth= fifth= sixth=
first=192 second= third= fourth= fifth= sixth=
first=192 second= third= fourth= fifth= sixth=
first=192 second= third= fourth= fifth= sixth=
first=192 second= third= fourth= fifth= sixth=

Please what am I doing incorrectly?


Solution

  • Your script looks like you should rewrite all of it in Awk; but here is a simple Bash script which hopefully offers at least a hint as to how your script could be simplified if you really want to write it in Bash.

    #!/bin/bash
    
    split () {
        local IFS='.'
        printf ' %s' $*
    }
    while read ptr fqdn; do
        ips=($(split "$ptr"))
        domain=${fqdn#*.}
        host=${fqdn%.$domain}
        echo "ipa dnsrecord-add ${domain%.} $host --a-rec ${ips[3]}.${ips[2]}.${ips[1]}.${ips[0]}"
    done <<\:
    251.2.168.192.in-addr.arpa core.admin.my.lan.
    :
    

    Output:

    ipa dnsrecord-add admin.my.lan core --a-rec 192.168.2.251
    

    Here's a quick and dirty Awk reimplementation.

    awk '{ split($1, rev, /[.]/); split($2, fqdn, /[.]/);
        domain=$2; sub("^" fqdn[1] "[.]", "", domain); sub(/[.]$/, "", domain);
        print "ipa dnsrecord-add", fqdn[1], domain,\
             "--a-rec", rev[4] "." rev[3] "." rev[2] "." rev[1] }' reverse_entries.txt