I am trying to write a function in bash that checks if a given hostname is present in /etc/hosts. Comments and partial matches should not count. In other words, it should only return 0 if exactly the specified hostname was found. This is what I got so far:
check_host()
{
AWK=$(awk '$1 ~ /^#/ { next } $2=="'$1'" {print $2}' /etc/hosts)
if [ -n "$AWK" ]; then
return 0
else
return 1
fi
}
I would prefer to use awk or grep to get the solution.
The function worked on my smaller local file, but it somehow failed on bigger ones; I am unsure of the reason. What am I missing? How could I improve or simplify my function?
I've already checked the following answer, but it does not work as expected: https://stackoverflow.com/a/25277451/157762