Bash eval-shell脚本中的Awk

Bash eval-shell脚本中的Awk,bash,shell,redirect,awk,eval,Bash,Shell,Redirect,Awk,Eval,我需要用awk构造命令并使用eval命令运行。我无法得到方法和引用命令。目标是找到正在运行的端口,并将带有日期的输出重定向到文件 #!/bin/bash curuser=$USER curworkdir=`pwd` log_dir="/tmp/logs" ports_log_file="${log_dir}/netstat_output.log" ports_not_listening="/tmp/logs/ports_not_listening.out" echo $log_dir echo

我需要用awk构造命令并使用eval命令运行。我无法得到方法和引用命令。目标是找到正在运行的端口,并将带有日期的输出重定向到文件

#!/bin/bash
curuser=$USER
curworkdir=`pwd`
log_dir="/tmp/logs"
ports_log_file="${log_dir}/netstat_output.log"
ports_not_listening="/tmp/logs/ports_not_listening.out"
echo $log_dir
echo $ports_log_file
if [[ ! -e $ports_log_dir ]]; then
    mkdir -p "$ports_log_dir"
fi
eval "netstat -na | grep [0-9]:80|awk -vabc=$ports_log_file 'BEGIN{"date"|getline d;}/80/{print d,\$0 >> abc  }'"
if [ $? -ne 0 ]; then
        echo "error port 80" >> $ports_not_listening
else
        echo "Print success for port-80: $?"    # expected result is 0 exit status
fi
cmd-out=$(netstat -na | grep [0-9]:8080|awk -vabc=$ports_log_file 'BEGIN{"date +'%Y-%m-%d-%r'"|getline d;}/8080/{print d,$0 >> abc  }')
if [ "$cmd-out" -ne 0 ]; then
        echo "error port 8080: $cmd_out" >> $ports_not_listening    #expected the return status not 0 for failure
else
        echo "Print success for port-8080: $?" #expected the return status 0 for successful run
fi
## mail the ports that are not listening
if [ -e "${ports_not_listening}" ] ; then
    ## mailx the ports that are not listening, for now just echo to stdout
    echo "$ports_not_listening"
fi
exit 0;

output expected:
2015-01-12-05:38:00 PM tcp        0     0 0.0.0.0:80 0.0.0.0:*                 LISTEN 
2016-01-13-05:39:02 PM tcp        0      0 0.0.0.1:8080              0.0.0.0:*                   LISTEN
谁能验证一下命令并纠正我如何引用。实现这一目标的正确方法是什么。

为什么不

$  netstat -na | 
   awk -v d="$(date)" '/[0-9]:80/ {f=1; print d,$0} 
                       END        {exit f?0:1}' >> $ports_log_file; echo $?

如果任何行匹配,则设置标志f,并使用补码作为退出状态。

与其说明
X-Y
问题,不如使用正确的输入和预期的输出清楚地说明您的要求。我确信有比这更好的方法,而不需要
eval
我正在使用这种方法来捕获netstat命令的返回状态。执行此命令后,需要检查“$?-eq 0”以确定执行的命令是否成功。您不需要
eval
。在shell上运行的任何命令都有一个存储在
$?
中的返回代码。您是否计划告知该要求?否则这将被关闭为非主题[!-e$ports\u log\u dir];然后mkdir-p“$ports\u log\u dir”fi eval“netstat-na | grep[0-9]:80 | awk-vabc=$ports\u log\u文件'BEGIN{“date”| getline d;}/80/{print d,\$0>>abc}'”if[$?-ne 0];然后echo“error port 80”>>$ports\u not\u listening else echo“port-80:$?”fi if[-e“${ports\u not\u listening}”];然后回显“$ports\u not\u listening”fi退出0;预期输出:2015-01-12-05:38:00下午tcp 0.0.0.0:80 0.0.0.0:*ListeneLegent解决方案。在我的脚本中,即使输出中没有运行端口,脚本也会成功。f标志和带?:运算符的结束块执行此操作。但在正则表达式中,它将匹配字符串端口80或其他端口,如80**(8080)。有没有办法只搜索特定的端口(没有额外的数字)。为此,您可能需要在80之后添加一个空格。有一个匹配命令来查找精确的字符串。命令是“match($0,/\y[0-9]:443\y/”,用于搜索模式。它起作用了。单词分隔符也可以。很高兴知道不同的方法。我也会尝试-F选项。