Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

save result to variable

Tags:

bash

netcat

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.

like image 482
user2129825 Avatar asked Mar 13 '13 16:03

user2129825


3 Answers

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)
like image 79
fedorqui 'SO stop harming' Avatar answered Oct 22 '22 03:10

fedorqui 'SO stop harming'


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.

like image 29
Mickaël Le Baillif Avatar answered Oct 22 '22 05:10

Mickaël Le Baillif


-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.

like image 36
Anuj Sethi Avatar answered Oct 22 '22 04:10

Anuj Sethi