简体   繁体   中英

AWK not behaving in bash Script

When running the ssh line from a command line, it works.

From a bash script, it appears as: ($ variables inside of awk command are empty)

ssh user@server.example.com netstat --tcp| grep 'servervip3'| grep 'ldap'| awk ' == ESTABLISHED'| awk '{print }'| awk -F: '{print }' >>/somepath/somefile.txt

Script Section:

    for (( i=0; i<${arraylength}; ++i ))
    do
       # drop all beyond first period in SSH_ADDRESS[i] and add vip3
       host_grep="`echo ${SSH_ADDRESS[i]}|awk -F. '{ print $1 }'`vip3"
         ssh $FIRSTLOGNAME@${SSH_ADDRESS[i]} netstat --tcp| grep '$host_grep'| grep 'ldap'| awk '$6 == "ESTABLISHED"'| awk '{print $5}'| awk -F: '{print $1}' >>$seed_file

done

Any ideas? Thanks -jim

Made some minor optimization over your original command as below with a strong dose of awk . I have combined 2 grep instances and an awk into one.

 ssh $FIRSTLOGNAME@${SSH_ADDRESS[i]} netstat --tcp | awk -v host="$host_grep" '(/host/ || /ldap/) && $6 == "ESTABLISHED" {print $5}' | awk -F: '{print $1}' >>$seed_file

I will explain how this works:-

  1. Store the hostname to search as an awk variable -v host="$host_grep" so that it will be useful in the regex match.
  2. (/host/ || /ldap/) && $6 == "ESTABLISHED" matches any line that has either host as stored in $host_grep or containing the keyword ldap AND having the column six value as "ESTABLISHED"
  3. awk -F: '{print $1}' delimits your string using : and prints the value before it.

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