Storage of the command result in variable portcheck does not work as expected. My script contains this method


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"
          echo "state unknown"

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?


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.

  • You will probably be better served using -o with nc to output the result to screen and then parse the file for the variable portcheck – Raman Sailopal Nov 17 '17 at 11:03
  • 3
    Looks to me like nc is outputting the results to stderr – Jeff Schaller Nov 17 '17 at 11:06

The nc call basically prints to stderr and you need to send the output to stdout as follows:

portcheck=$(nc -z -v -w5 localhost 8443 2>&1)
echo "*${portcheck}*"

This would be the output, in this case:

*Connection to localhost 8443 port [tcp/*] succeeded!*

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.