Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Script Help Pse 1

Status
Not open for further replies.

MarkThomo

Technical User
Nov 3, 2001
1
AU
I need to write a ksh shell script that will allow me to input the name of 1 of the computers/printers on the school network and will return the IP address of that host, the script needs to access the /etc/hosts to get the information and if the host is not found in the /etc/hosts file then output a message that the hostname cannot be located.

I only have basic script writing skill and and help would be greatly appreciated

many Thanks

Mark
 
Hi Mark,

Unix has got some good tools to do this kind of thing.

This is actually three jobs:

1 - search thru the file
2 - detect whether the host name is in there
3 - print JUST the IP address if it is
- print 'Not found' if it isn't

You can search through a file for some text with the 'grep' command, like this:
[tt]
grep host_name /etc/hosts
[/tt]

and, assuming that the string host_name is in the file, grep will print out any line containing the string you've specified.

You can tell if a unix command worked by examining its return code, if it worked it will be zero.

The return code is in $?

so you can tell if a grep found something like this:
[tt]
grep string file > /tmp/a_file 2>&1
if [[ $? eq 0 ]]
then
[tab]echo "found it"
else
[tab]echo "didn't find it"
fi
[/tt]


Next, and last - pick out the IP address from the output of grep

Easy one this - use awk

Awk is a complex utility that's difficult to learn completely, but it can do some simple things very easily

In the file /tmp/a_file that was created above (by grep) is a line like this:
[tt]
192.168.100.3[tab]holly
[/tt]

you just want the first bit, the ip address
like this:
[tt]
cat /tmp/a_file | awk '{print $1}'
[/tt]


That should give you all of the bits you need to put together to make a working script. Get back to us if you need help with any particular bit.

Regards
Mike
michael.j.lacey@ntlworld.com
Email welcome if you're in a hurry or something -- but post in tek-tips as well please, and I will post my reply here as well.
 
You can use this simple script shell.

#!/usr/bin/ksh
ip=$(grep $1 /etc/hosts | awk '{print $1}')
echo ${ip:-"not found"}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top