user2962912
user2962912

Reputation: 79

passing output of a netcat command to a variable or piping through read utility

The output of the netcat command nc - dvzw1 8.8.8.8 443 does not appear to behave in the way that output from other commands have predictably worked when stored in a variable or piped through the read utility.

  1. Storing the nc cmd output to a variable cmd_output=$(nc -dvzw1 8.8.8.8 443) produces an empty variable. Same result without the v switch. Other cmds can be stored to variable (ls -a, pwd, date).

  2. Piping the nc output to the read utility as below writes nothing to the file. Same result without the v switch.

nc -dvzw1 8.8.8.8 443 | while read line ; do echo -e "$now $line" ; done >> ~/vpn.log

The 'while read echo' pipe has worked with another command. I can also redirect the nc command output directly to file ( ie: without piping to 'while read echo').

Upvotes: 3

Views: 5611

Answers (1)

KamilCuk
KamilCuk

Reputation: 140880

> nc -dvzw1 8.8.8.8 443
Connection to 8.8.8.8 443 port [tcp/https] succeeded!

The Connection to 8.8.8.8 443 port [tcp/https] succeeded! is written into stderr, standard error. The $( ... ) command substitution captures standard output of a command.

You can ex. redirect standard error to standard output: nc -dvzw1 8.8.8.8 443 2>&1.

If you just want to check if the nc command succeeded, just check it's exit status, ex. using if if nc -dvzw1 8.8.8.8 443 2>/dev/null; then echo "Succeeded"; else echo "failed"; fi or by inspecting $?.

Upvotes: 8

Related Questions