Question

I am trying to use awk to extract part of its output and assign that to a variable but I cannot get AWK to work.

This is the command I am running:

nc -v -z 192.168.8.216 9100 | awk '{print $NF}'

This is the output

Connection to 192.168.8.216 9100 port [tcp/*] succeeded!

What I am trying to achieve is so that the output is only

succeeded

I just want the last part of the command so that I can assign it to a variable and run an if statement.

Was it helpful?

Solution

The command seems to be sending the output to STDERR and not to STDOUT.

Merge the STDERR with STDOUT:

nc -v -z 192.168.8.216 9100 2>&1 | awk '{print $NF}'

I just want the last part of the command so that I can assign it to a variable and run an if statement.

If the purpose is to simply determine that the command produced the word succeeded, you don't need a variable:

[[ $(nc -v -z 192.168.8.216 9100 2>&1) =~ succeeded ]] && echo "Yes"

If you want to match the ! too and ensure that it was at the end of line:

[[ $(nc -v -z 192.168.8.216 9100 2>&1) =~ succeeded\!$ ]] && echo "Yes"

OTHER TIPS

Try using the exit status:

nc -v -z 192.168.8.216 9100 && echo 'Yes' || echo 'No'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top