1

I made a very simple script (ping_hostnames.sh) to go through a list of IP's/hostnames in a file hostnames.txt and ping them:

#!/bin/bash

hostnameCount=`cat hostnames.txt | wc -l`
i=1

while [ $i -le $hostnameCount ]
do
  ping -c 3 $(sed -n ${i}p hostnames.txt)
  i=$(( i+1 ))
done

I then do:

cat file_with_ip_list.txt >> hostnames.txt

The hostnames.txt now looks like:

192.168.1.0
192.168.1.1
192.168.1.2
192.168.1.3

Then running the script (./ping_hostnames.sh) gives an error:

: Name or service not known

However, if I manually copy/paste the data from file_with_ip_list.txt to hostnames.txt with a text editor, it works just fine. Is there some sort of type casting going on with cat or something?

7
  • Welcome, what is the content of hostnames.txt? Commented Mar 1, 2021 at 21:39
  • 4
    Most likely file_with_ip_list.txt has Windows-style (CRLF) line endings Commented Mar 1, 2021 at 21:41
  • 1
    The file has been copied from Windows to RedHat so that's probably it, didn't know that was a thing. How would I know that in the future?
    – timmio888
    Commented Mar 1, 2021 at 21:44
  • 2
    Unrelated to your actual question: Instead of cat hostnames.txt | wc -l, use wc -l hostnames.txt. Actually, you don't need the wc at all, and your loop could be like this: for host in $(cat hostnames.txt); do ping -c3 "$host"; done Commented Mar 1, 2021 at 22:44
  • 1
    Don't use for host in either -- to read a file line-by-line, use a while read ... loop. See BashFAQ #1: How can I read a file (data stream, variable) line-by-line (and/or field-by-field)? Note: if you use while IFS=$'\r' read ... (and are using bash, not a brand-x shell), it'll auto-trim the carriage return from the end of the line. Commented Mar 2, 2021 at 10:21

2 Answers 2

1

@steeldriver in the comments answered it: "invisible" CRLF line endings caused this issue, and now that I know, I can use numerous workarounds to this. Also, thank you to everyone else in the comments for helping me improve my code! While I'm not a complete newbie to BASH, I still have much to learn!

0

See if this will work with the hostname.txt. It might be that wc -l is getting the line count off by one or something like that.

for f in $(cat hostnames.txt); do ping -c 3 ${f}; done

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .