bash 将 IP 转换为 FQDN 的脚本仅适用于最后一个条目

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

我有以下 bash 脚本,它读取 IP 地址的文本文件,然后 运行s 主机命令并仅提取 fqdn 并在末尾删除句点。该命令适用于我的文本文件中的每个 IP,但是当我尝试 运行 只有最后一个 IP 有效时?

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

这是我得到的输出

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

hosts.txt 结果是问题所在 hosts2.txt 有效但不确定原因

替换

cat hosts.txt

dos2unix < hosts.txt

摆脱你的马车returns。

您可以设置I内部F字段S分离器环境变量IFS 无论是接受 Unix 还是 DOS 换行符:

#!/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