Problem:
Storage of the command result in variable portcheck does not work as expected.
My script contains this method
#!/bin/bash
...
status() {
portcheck=$(nc -z -v -w5 localhost 8443)
echo "*${portcheck}*"
if [[ $portcheck == *refused* ]]; then
echo "Application is stopped"
elif [[ $portcheck == *succeeded* ]]; then
echo "Application is started"
else
echo "state unknown"
fi
}
When I execute myscript, I get this result:
> $ ./myscript status
> Connection to localhost 8443 port [tcp/*] succeeded!
> **
> state unknown
But what I would like to have is that the result of the command is stored in varaible portcheck and the output should look like
> $ ./myscript status
> Connection to localhost 8443 port [tcp/*] succeeded!
> *Connection to localhost 8443 port [tcp/*] succeeded!*
> Application is started
I tried several variants according https://stackoverflow.com/questions/4651437/how-to-set-a-variable-to-the-output-from-a-command-in-bash and others e.g.
portcheck=`nc -z -v -w5 localhost 8443`
instead of
portcheck=$(nc -z -v -w5 localhost 8443)
But it didn't work. What am I doing wrong?
Background:
The command
nc -z -v -w5 localhost 8443
checks if the port is connectable. It returns
Connection to localhost 8443 port [tcp/*] succeeded!
if port is "open" and
nc: connect to localhost port 8443 (tcp) failed: Connection refused
if port is "closed".
This works fine if I just execute the command plain in the bash.