Search code examples
bashmacosipcarriage-returnfqdn

bash scrip to convert IPs to FQDN only works on last entry


I have the following bash script which reads a text file of IP addresses and then runs the host command and pulls out just the fqdn and drops the period on the end. The command works for every IP in my text file but when I try and run this only the last IP works?

#!/bin/bash
cat hosts.txt | while read -r output
do 
    host $output | awk 'NR==1{print $5}' | sed 's/.$//'
done > results.txt

Here is the output I get

3(NXDOMAIN
3(NXDOMAIN
3(NXDOMAIN
3(NXDOMAIN
3(NXDOMAIN
dsfprmtas07.mydomain.com

hosts.txt turned out the be the issue hosts2.txt works but not sure why


Solution

  • You can setup the Internal Fields Separator environment variable IFS to accept either Unix or DOS newlines regardless:

    #!/usr/bin/env bash
    
    # Accept Unix or DOS newlines regardless as record delimiters
    IFS=$'\n\r '
    
    while read -r ip_addr
    do
      # Read the fully qualified domain name as fifth field
      # by reading first 4 fields into _ placeholders
      read -r _ _ _ _ fqdn < <(host "$ip_addr")
    
      # Strip trailing dot of FQDN to get the host_name
      host_name="${fqdn%.}"
    
      # Just print
      echo "$host_name"
    done <hosts.txt