R
R
RiGs2019-09-13 18:54:40
linux
RiGs, 2019-09-13 18:54:40

Bash check for an open port. How to check the output of a command?

There is a task using a bash script to check if the port is open and, depending on the result, perform one or another action.
I can not figure out how to check the result of the NC command in the if condition, something like this

#!/bin/bash

RESULT=$(nc -z <host> <port>)

if [$RESULT]; then
echo 'Открыт'
else
echo 'Закрыт'
fi

but not working

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
ky0, 2019-09-13
@Rigs

https://stackoverflow.com/a/14701003

S
Saboteur, 2019-09-13
@saboteur_kiev

Variable $? contains the result of the last executed command (0=success)

#!/bin/bash

nc -z <host> <port>

if [ $? -ne 0 ]; then
echo 'Открыт'
else
echo 'Закрыт'
fi

3
3vi1_0n3, 2019-09-17
@3vi1_0n3

Bash script without nc, using the same $?

echo "" > /dev/tcp/192.168.1.10/443 && echo "Opened" || echo "Closed"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question