I am trying to create script which can let me to put number of port as parameter and then find the name of service for this port.
Here is the script:
#!/bin/bash
grep -E "\W$1\/" /etc/services | awk '{ print $1 }'
if [ $? -eq 0 ]; then
echo "Service(s) is(are) found correctly!"
else
echo "There is(are) no such service(s)!"
fi
Everything works perfectly but there is one problem. If I type such port as 99999 (or another fiction port) – "exit status" for grep -E "\W$1\/" /etc/services | awk '{ print $1 }'
also will be 0. In this way all results of my scripts will be correct and else
statement in my script won't work. What am I going to do to find the solution to this problem and let my else
works fine with "exit status"?
Best Answer
You don't need
grep
here at all,awk
can do the pattern match on the port number.awk
can also keep track of whether the port was found or not and exit with an appropriate exit code.For example:
The
exit !found
works becauseawk
variables default to zero (or true) if they haven't previously been defined -exit !0
isexit 1
. So if we setfound=1
when we match thenexit !found
in the END block isexit 0
.Here's how to use that awk script with your if/then/else.
You can also do it like this:
Or even like this: