Shell Script stuck when "nc" destination connection fails

Hi KMers,

I am trying a very simple macro to execute a shell script that runs "nc" to check connectivity.

When I run the macro with "nc" to a destination that I have connecitivity to, things work (i.e. result window pops up, and subsequent actions ran) - when the "Include Errors" is enabled. Example below
image

image

My challenge is that when the "nc" runs against a destination that I don't have connectivity to, i.e. either connection refused or timeout, the macro is stuck, i.e. no pop-up display result window and any subsequent actions will not run. Screenshot below

I have tried the following, but none worked.

  • Enable "Include Errors"
  • Including the shebang line in the script, i.e. "#!/bin/bash"
  • try other similar package, i.e. ncat, telnet.

The following is a screenshot of executing the command directly from Terminal.
image

I can run the shell script directly outside KM. But this is bugging me and would like to get it working with KM. (so that I can centralise all my script execution from KM).

Thanks

Hi, @tt42. Try the method included in this macro.

Download: Test Host-Port Connection Using nc.kmmacros (10 KB)

Macro-Image


Macro-Notes
  • Macros are always disabled when imported into the Keyboard Maestro Editor.
    • The user must ensure the macro is enabled.
    • The user must also ensure the macro's parent macro-group is enabled.

System Information
  • macOS 13.5.1 (22G90)
  • Keyboard Maestro v10.2

1 Like

Thank you, @_jims Your solution works like a charm:)

If possible, I’d very much like to understand why KM doesn’t trigger the pop-up result notification or subsequent action when using the script to directly run “nc” in the error scenarios. Any input on that would be much appreciated.

Hi, @tt42. If you check the nc man page, you'll see this:

In the macro I supplied above, you'll see:

msg=$(nc -z -v $host $port 2>&1)

In Bash, 2>&1 is an operator that redirects stderr to the same destination as stdout; i.e., it merges the error output with the regular output. For more information, see: Bash — pipes and redirections. stdin, stdout and stderr

Try this simplified macro:

Download: Test Host-Port Connection Using nc (method B).kmmacros (9.7 KB)

Macro-Image


Macro-Notes
  • Macros are always disabled when imported into the Keyboard Maestro Editor.
    • The user must ensure the macro is enabled.
    • The user must also ensure the macro's parent macro-group is enabled.

System Information
  • macOS 13.5.1 (22G90)
  • Keyboard Maestro v10.2

In that macro in the Execute a Shell Script actions, I selected Include Errors.

If you unselect Include Errors, you'll see that the nc command does indeed return all information via stderr.

This is very help, @_jims. Much appreciated!

1 Like