简体   繁体   中英

Awk in eval - shell scripting

I need to construct the command with awk and run using eval command. I could not get the approach and quoting the commands. Goal is to find the ports running and redirect the output with date to file.

#!/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

could anyone verify the command and correct me how to quote. what would be right approach to achieve this.

why not just

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

if any line matches sets the flag f, and uses the complement as the exit status.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM