我需要使用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谁能验证命令,并纠正我如何引用。什么才是实现这一目标的正确方法。
发布于 2017-02-16 02:25:00
为什么不干脆
$ netstat -na |
awk -v d="$(date)" '/[0-9]:80/ {f=1; print d,$0}
END {exit f?0:1}' >> $ports_log_file; echo $?如果有任何行匹配,则设置标志f,并使用补码作为退出状态。
https://stackoverflow.com/questions/42255685
复制相似问题