I quite this script in bash:

probe='nc -zv localhost 19997'
output=' grep -c 'succeeded' $probe'
if [ $output == '0' ]
     echo 'Client online'
     echo 'Offline'

The purpose of the script is to check via netcat if a client connected via reverse ssh to my server on port 19997 and print a positive message if this was detectet. nc would print

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

if it detects the client and I would like to grep only the 'succeeded' as a keyword for the established connection and trigger the if-statement via the exit code of grep. But when i run this script I get:

test.sh: line 3: [: too many arguments

Where did I do wrong?

  • 2
    You are assigning strings to your variables. You want to use command substitution probe=$(nc...). And quote your expansions: [ "$output" == '0' ].
    – PesaThe
    Dec 27 '17 at 20:02
  • 2
    You confused a single quote character ' with backqoute `.
    – jimmij
    Dec 27 '17 at 20:03
  • 1
    Paste your shell scripts in at shellcheck.net to catch these sorts of syntax errors. Dec 27 '17 at 20:05

You can test on the results of the command directly like so:

if ( nc -zv localhost 19997 2>&1 >/dev/null ); then
    echo 'Online'
    echo 'Offline'

the subshell ( ... ) is not necessary but I like using them when testing like this for cleanliness.

For more reading on exit codes and testing see:

  • I tried to depend the if-statement of the exit-code of grep, but your solution works much better. Many thanks!
    – t3ngu
    Dec 27 '17 at 20:09
  • This is a very elegant solution Dec 28 '17 at 4:33

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.