Reputation: 81
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.
Upvotes: 8
Views: 9970
Reputation: 1
For anyone who might come across this question by searching or from google, wondering why a successful connection saved to a $var
returns an empty string, according to this reddit post "All messages from nc itself, as opposed to from the socket, are printed to stderr." So as mentioned by fedorqui and Mickael, you have to redirect stderr
to stdout
even though it doesn't seem like you're getting an error message.
Example of output to terminal but empty output when calling your $var
:
var=$(nc -z -w 10 www.google.com 80)
outputs Connection to www.google.com port 80 [tcp/http] succeeded!
to the terminal, but when calling echo $var
it displays an empty string even though the connection was successful.
Example of saving the stderr
output to the $var
:
var=$(nc -z -w 10 www.google.com 80 2>&1)
runs the nc command, then calling echo $var
no longer outputs an empty string, but instead the expected success message Connection to www.google.com port 80 [tcp/http] succeeded!
.
Upvotes: 0
Reputation: 21
-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.
Upvotes: 2
Reputation: 290275
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)
Upvotes: 14
Reputation: 2156
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
.
Upvotes: 4