我正在尝试创建脚本,该脚本可以让我将端口号作为参数,然后找到该端口的服务名称。这是脚本:
#!/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
一切正常,但是有一个问题。如果我输入诸如99999(或其他小说端口)的端口-的“退出状态”grep -E "\W$1\/" /etc/services | awk '{ print $1 }'
也将为0。这样,我脚本的所有结果都将是正确的,并且else
脚本中的语句将不起作用。我该怎么做才能找到解决此问题的方法,并让我的else
工作状态为“退出状态”,该怎么办?
您根本不需要grep
这里,awk
可以在端口号上进行模式匹配。
awk
还可以跟踪是否找到了该端口,并使用适当的退出代码退出。
例如:
$ port=23
$ awk '$2 ~ /^'"$port"'\// {print $1 ; found=1} END {exit !found}' /etc/services
telnet
$ echo $?
0
$ port=99999
$ awk '$2 ~ /^'"$port"'\// {print $1 ; found=1} END {exit !found}' /etc/services
$ echo $?
1
在exit !found
因为作品awk
变量默认为零(或真),如果他们以前没有被定义-exit !0
是exit 1
。因此,如果我们设置found=1
匹配的时间exit !found
,则END块中的exit 0
。
这是在您的if / then / else中使用该awk脚本的方法。
#!/bin/bash
awk '$2 ~ /^'"$1"'\// {print $1 ; found=1} END {exit !found}' /etc/services
if [ $? -eq 0 ]; then
echo "Service(s) is(are) found correctly!"
else
echo "There is(are) no such service(s)!"
fi
您也可以这样:
if awk '$2 ~ /^'"$1"'\// {print $1;found=1} END{exit !found}' /etc/services ; then
echo "Service(s) is(are) found correctly!"
else
echo "There is(are) no such service(s)!"
fi
甚至像这样:
awk '$2 ~ /^'"$1"'\// {print $1 ; found=1} END {exit !found}' /etc/services \
&& echo "Service(s) is(are) found correctly!" \
|| echo "There is(are) no such service(s)!"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句