0

I was trying to read a file line by line(each line is a hostname), do some processing like this :

while read -r line
do 
  if ping -c1 $line
     echo $line is running  
  fi 
done <file.txt 

I found that the out put is like this:

  is running
  is running 
  ...

As if the variable $line is empty.

Thanks to all who commented this question. I think I now understand what happened.

So the file has CRLF line ending. And the length of a line is exactly the same as is running.

Because of the CR character at the end of $line, the content of $line gets completely overwritten by is running. If only the length of a line is longer, I would have asked the question differently.

peterh
  • 9,488
  • 16
  • 59
  • 88
SparedWhisle
  • 3,588
  • 4
  • 22
  • 35
  • What is the contents of the file? Does `$line` start with a dash (`-`)? What if you use `printf '%s is ok' "$line"`? – Kusalananda Jun 08 '18 at 06:55
  • Does `file.txt` have Window-style (CRLF) line endings? – steeldriver Jun 08 '18 at 06:55
  • if I add a `echo $line` after `fi`, aka outside of the if block, it would work perfectly. The text file contains a list of hostnames, lines don't start with dash. I'm sure the content can be read ok as `echo ` outside of the if works. – SparedWhisle Jun 08 '18 at 07:01
  • @steeldriver yes I think it has CRLF line endings – SparedWhisle Jun 08 '18 at 07:10
  • @steeldriver thanks, it now works ok after I change line ending of the file. Would you mind explain why it worked outside of `if` previously? – SparedWhisle Jun 08 '18 at 07:15
  • 1
    You have now edited the code in the question so that the text no longer matches up with it. Please edit it again so that we can see what code you are actually running. – Kusalananda Jun 08 '18 at 07:18
  • Well you've changed the question now - when you `echo $line is ok` and `$line` ends in CR then ` is ok` will overwrite the start of `$line` – steeldriver Jun 08 '18 at 07:20
  • I'm getting very much confused myself now. please ignore my question for now. I'll do some more testing and update my question later. Sorry guys! – SparedWhisle Jun 08 '18 at 07:28
  • The output of your two `echo` statements in your edited code should be the same no matter what line endings the file has. – Kusalananda Jun 08 '18 at 07:30
  • Thank you all guys. I didn't realize the string I put in echo mattered, and I didn't realize it's a CR character problem. So I just wrote a random echo string `test 1`, `test 2` which were totally misleading and incorrect. I have now corrected the question, everything should make sense now. Sorry guys for the trouble. – SparedWhisle Jun 08 '18 at 07:45

0 Answers0