根据鸟哥的教材写的一个shellscript
testing=$(netstat -tun | grep ":80 ") # 偵測看 port 80 在否?
if [ "$testing" != "" ]; then
echo "WWW is running in your system."
fi
testing=$(netstat -tun | grep ":22 ") # 偵測看 port 22 在否?
if [ "$testing" != "" ]; then
echo "SSH is running in your system."
fi
testing=$(netstat -tun | grep ":21 ") # 偵測看 port 21 在否?
if [ "$testing" != "" ]; then
echo "FTP is running in your system."
fi
testing=$(netstat -tun | grep ":25 ") # 偵測看 port 25 在否?
if [ "$testing" != "" ]; then
echo "Mail is running in your system."
fi
我直接netstat -tun,目前是只有tcp80端口的链接,根本没有SSH、FTP、MAIL的链接,根据以上shell的判断,运行结果照例是会只输出显示"WWW is running in your system.",但是我实际输出结果却是四个echo都显示了出来,请问为何?
大侠帮我看看这if fi的shellscript为何会运行不正常?
-
- 帖子: 76
- 注册时间: 2010-11-27 22:20
- 灰色小狼
- 帖子: 4585
- 注册时间: 2008-12-06 10:38
- 系统: Arch
Re: 大侠帮我看看这if fi的shellscript为何会运行不正常?
if判断后为什么要写分号?
- eexpress
- 帖子: 58428
- 注册时间: 2005-08-14 21:55
- 来自: 长沙
Re: 大侠帮我看看这if fi的shellscript为何会运行不正常?
分清楚是字符串比较,还是数值比较。变量别用“”包裹。
结果赋值,根本不需要。你应该判断$?。
netstat -tun | grep ':80 '
[ $? ] && echo no || echo yes
结果赋值,根本不需要。你应该判断$?。
netstat -tun | grep ':80 '
[ $? ] && echo no || echo yes
● 鸣学
-
- 帖子: 49
- 注册时间: 2006-11-27 14:21
- 联系:
Re: 大侠帮我看看这if fi的shellscript为何会运行不正常?
我这里运行你的脚本是正常的,我测试了启动和不启动WWW,启动和不启动SSH,结果如预期。
- astolia
- 论坛版主
- 帖子: 6445
- 注册时间: 2008-09-18 13:11
Re: 大侠帮我看看这if fi的shellscript为何会运行不正常?
在代码前加个
set -x
再运行看看问题出在哪里
set -x
再运行看看问题出在哪里
- byZh
- 帖子: 198
- 注册时间: 2009-01-11 21:38
Re: 大侠帮我看看这if fi的shellscript为何会运行不正常?
楼主的脚本是可以正常运行的,但根据楼主的命令判断会出问题
我的系统根本没有运行WEB服务,但脚本输出“WWW is running in your system.”
其实只是我的系统访问外面的web服务,所以还是根据ps命令的输出来判断比较靠谱
另外我比较习惯下面的写法:
[bash]
if ps -ef | grep [h]ttpd >/dev/null 2>&1;then #httpd服务
echo "WWW is running in your system."
fi
[/bash]
我的系统根本没有运行WEB服务,但脚本输出“WWW is running in your system.”
其实只是我的系统访问外面的web服务,所以还是根据ps命令的输出来判断比较靠谱
另外我比较习惯下面的写法:
[bash]
if ps -ef | grep [h]ttpd >/dev/null 2>&1;then #httpd服务
echo "WWW is running in your system."
fi
[/bash]
以缺德服人......
- fanhe
- 帖子: 2357
- 注册时间: 2007-03-24 23:45
-
- 帖子: 6548
- 注册时间: 2008-10-31 22:12
- 系统: 践兔
- 联系:
Re: 大侠帮我看看这if fi的shellscript为何会运行不正常?
代码: 全选
tlcr: 0 庚寅年十二月廿一日 9:48 ~
● dog > /tmp/test
testing=$(netstat -tun | grep ":80 ") # 偵測看 port 80 在否?
if [ "$testing" != "" ]; then
echo "WWW is running in your system."
fi
testing=$(netstat -tun | grep ":22 ") # 偵測看 port 22 在否?
if [ "$testing" != "" ]; then
echo "SSH is running in your system."
fi
testing=$(netstat -tun | grep ":21 ") # 偵測看 port 21 在否?
if [ "$testing" != "" ]; then
echo "FTP is running in your system."
fi
testing=$(netstat -tun | grep ":25 ") # 偵測看 port 25 在否?
if [ "$testing" != "" ]; then
echo "Mail is running in your system."
fi
tlcr: 0 庚寅年十二月廿一日 9:48 ~
● bash /tmp/test
WWW is running in your system.
tlcr: 0 庚寅年十二月廿一日 9:48 ~
● dash /tmp/test
WWW is running in your system.
tlcr: 0 庚寅年十二月廿一日 9:48 ~
● sh /tmp/test
WWW is running in your system.
tlcr: 0 庚寅年十二月廿一日 9:48 ~
●
代码: 全选
] ls -ld //