How can I save result from nc to the variable?
I want:
nc: connect to localhost port 1 (tcp) failed: Connection refused
on my variable. I tried:
a="$(nc -z -v localhost 1)"
echo $a
but output is empty.
Just use $() to get the result of the command:
your_var=$(nc -z -v localhost 1)
If you also want the error to be stored, then redirect the 2 (error) to 1 (normal output):
your_var=$(nc -z -v localhost 1 2>&1)
Just redirect stderr to stdout, expressed by 2>&1:
a="$(nc -z -v localhost 1 2>&1)"
echo $a
nc: connect to localhost port 1 (tcp) failed: Connection refused
File descriptor 2 is attached (unless redirected) to stderr, and fd 1 is attached to stdout. The bash syntax $( ... ) only captures stdout.
-w is your friend in this case
-w timeout Connections which cannot be established or are idle timeout after timeout seconds. The -w flag has no effect on the -l option, i.e. nc will listen forever for a connection, with or without the -w flag. The default is no timeout.
nc -z -w 3 $serverName $serverPort
Now you can use the $? variable to use it in your script.
if [ $? == 0 ] can be used to use the output of above command in the scripts.
Above command will timeout the connection after 3 seconds if it not able to establish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With