linux 脚本运行报错 无法找到字符串

#!/bin/bash
pids=`lsof -i:9090|awk '{if(NR!=1&&$10=="(CLOSE_WAIT)")print $2}'`
listen=`lsof -i:9090|awk '{if(NR!=1&&$10=="(LISTEN)")print $2}'`
echo $pids
echo $listen
if [$pids];
then
   for pid in $pids
   do
      echo "kill process $pid"
      kill -9 $pid
   done
elif [$listen];
then
    echo "asdasdas" 
    echo "$listen already processing"
          
else     
    /bin/java -cp "/root/BOOT-INF/classes:/root/BOOT-INF/lib/*" com.spider.unidbgserver.UnidbgServerApplication
    echo "start process"
fi   

运行脚本后如下

root@center1:~# sh unidbg_new.sh 

25511
unidbg_new.sh: 6: unidbg_new.sh: []: not found
unidbg_new.sh: 14: unidbg_new.sh: 1: not found

为啥这个字符串[$pids] 和[$listen] 总是找不到呢?求解

阅读 1.6k
1 个回答

建议重学 shell
if 关键字后跟命令
[test 命令的别名
注意,他是一个命令
也就是说后面的什么 $pids 啊,= 啊,甚至 ] 都是 [ 的参数
所以你得用空格隔开他们
另外你得给 [ 里面的变量加双引号,要么用 [[ ]]
你细品这个报错信息

unidbg_new.sh: 6: unidbg_new.sh: []: not found
unidbg_new.sh: 14: unidbg_new.sh: 1: not found

$listen 为空,[ $listen ] 就变成 [ ],就爆炸了
那用 [ "$listen" ] 的话,即使 $listen 为空,[ "" ] 也是合法的
综上,

- if [$pids];
+ if [ "$pids" ]
- elif [$listen];
+ elif [ "$listen" ];
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题