Solved My code returns wrong result

Hello,

Could someone please tell me why the code bellow return 2 lines of results?
Code:
ListenAddress 199.115.205.163
199.115.205.163
I was only expect to see
Code:
ListenAddress 199.115.205.163

Here is my code
Code:
#!/bin/sh
#
# services must only listen on their own IP
hostname=$(hostname -s)
hname=$(grep $hostname /etc/hosts | awk '{print $1}')
echo "ListenAddress $hname" >> sshd_config
 
Yep, there's probably two lines with the hostname in /etc/hosts, resulting in two IP addresses.

If there's something like this in hosts
Code:
1.2.3.4 shortname
1.2.3.4 shortname.my.domain

A grep on the shortname will match both lines.
 
SirDice
Yes I have the following in the /etc/hosts
Code:
199.115.205.163         garfield.mydomain.co.uk garfield
199.115.205.163         garfield.mydomain.co.uk
Could you please help me to find a workaround this issue?
 
I'd also remove that second line from the hosts file. It's useless because it's already defined on the first line.
 
Another obvious simple solution without having to understand awk or more advanced shell code, you could just add a head -n 1 or tail -n 1 into the original pipe in order to return the first of last matching line from the file.

I think we may be over-thinking the problem a bit though worrying about the order of entries in hosts. Both the lines have the same address, and as SirDice said, the obvious fix is to just remove the second line from /etc/hosts in the first place. If this script was actually being released as part of some application rather than just a simple hack for one user, then the extra effort to get the right entry from hosts might be worth it.
 
Thank yo guys.. :)
The script is part of my jail flavour script.
I decided to removed the duplicate line in the /etc/hosts file as it is not needed
 
If this script was actually being released as part of some application rather than just a simple hack for one user, then the extra effort to get the right entry from hosts might be worth it.
The fix is easy, and when a problem like this turns up, it is likely to happen the next time, too. So it usually pays off to do it right, even in throwaway scripts. Such scripts often have much longer lives than anticipated. Even if they don't, the memory of the problem and having solved it can be useful the next time around.
 
Back
Top