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.
$line
start with a dash (-
)? What if you useprintf '%s is ok' "$line"
? – Kusalananda Jun 08 '18 at 06:55file.txt
have Window-style (CRLF) line endings? – steeldriver Jun 08 '18 at 06:55echo $line
afterfi
, 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 asecho
outside of the if works. – SparedWhisle Jun 08 '18 at 07:01if
previously? – SparedWhisle Jun 08 '18 at 07:15echo $line is ok
and$line
ends in CR thenis ok
will overwrite the start of$line
– steeldriver Jun 08 '18 at 07:20echo
statements in your edited code should be the same no matter what line endings the file has. – Kusalananda Jun 08 '18 at 07:30test 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