1

I wish to club the below two Steps whereby the output of Step 1 i.e the PORTS should go as input to Step 2.

Step 1:

The below command gets me the port numbers from a file.

genpwdfile dec -in test/test.cfg -out /tmp/dec.out |grep PORT_NUM /tmp/dec.out | cut -d '=' -f2 ; grep MONITOR_PORT /tmp/dec.out  | cut -d '=' -f2

Output:

33027
13041

Step 2:

The below command kills the PID [which comes as output of Step 1] occupying the ports.

lsof -i:33027 2>/dev/null | grep -v PID | awk '{print $2}' | xargs kill -9

lsof -i:13041 2>/dev/null | grep -v PID | awk '{print $2}' | xargs kill -9

Sample /tmp/dec.out

Test_DIR=/tmp
PORT_NUM=33027
TEST_PORT_WORK=7777
MONITOR_PORT=13041

I'm dealing with AiX 6.1 System

Can you please suggest ?

Ashar
  • 491
  • What is the point of the genpwdfile command if you then just grep PORT_NUM /tmp/dec.out? You aren't connecting these in any way. – terdon Nov 23 '20 at 10:22
  • The genpwdfile creates dec.out file – Ashar Nov 23 '20 at 11:06
  • Then why are you piping to grep PORT_NUM /tmp/dec.out? And what does the second grep do? The one in grep MONITOR_PORT /tmp/dec.out? – terdon Nov 23 '20 at 11:08

1 Answers1

1

Just use a shell loop. You can join your two grep commands into a single one, and there's no point in piping the genpwdfile if it creates a file. Try this:

genpwdfile dec -in test/test.cfg -out /tmp/dec.out &&
    grep -E 'PORT_NUM|MONITOR_PORT' /tmp/dec.out | cut -d '=' -f2 |
        while read -r port; do
            lsof -i:"$port" 2>/dev/null | 
                awk 'NR>1{print $2}' 
        done | xargs kill -9 
terdon
  • 242,166
  • The answer did not help! the two grep in Step1 gets me two ports. The answer | while read -r port; do only reads one port and does not loop twice for each port. Also, ... | cut -d '=' -f2 ; grep MONITOR_PORT /tmp/dec.out | ... gets me the second port number. two greps returns two port numbers. – Ashar Nov 23 '20 at 13:17
  • @Ashar thanks for the edit, that made things clearer. Try the updated answer. – terdon Nov 23 '20 at 15:54
  • grep 'PORT_NUM\|MONITOR_PORT' /tmp/dec.out doesn't grep for both entries in the file for the AiX I have. – Ashar Nov 23 '20 at 16:06
  • @Ashar really? I could have sworn the \| was completely portable. Does it work if you change that to grep -E 'PORT_NUM|MONITOR_PORT' /tmp/dec.out? – terdon Nov 23 '20 at 16:08
  • grep -E 'PORT_NUM|MONITOR_PORT' /tmp/dec.out Works !! but grep 'PORT_NUM\|MONITOR_PORT' /tmp/dec.out does not. – Ashar Nov 23 '20 at 16:22
  • @Ashar OK. I have no idea why, but maybe the \| is a GNU extension. So, does the updated answer work? – terdon Nov 23 '20 at 16:27