2

I am trying to write a while loop in bash as below:

while [!(netstat -pnlt | grep ":9393" | wc -l)];
do
    echo "server not ready... waiting..."
    sleep 2
done

I get

syntax error near unexpected token `netstat'

from console

what I want to do is:

to grep the service that using port 9393, count its lines. If lines number is 0, it means the service is not running, so I will keep it wait.

OS: debian:jessie

please help me correct it... I looked up a lot of documents

0

2 Answers 2

2

Your test syntax is incorrect. Have a look at the man page for usage, or at the examples all over the Internet.

while [[ $(netstat -pnlt | grep -c ":9393 .*LISTEN") -eq '1' ]]; do
    echo "server not ready... waiting..."
    sleep 2
done

But with the edit you made to your question, the following would be better:

while ! netstat -pnlt | grep -q ":9393 .*LISTEN"; do
    echo "server not ready... waiting..."
    sleep 2
done
Sign up to request clarification or add additional context in comments.

Comments

2

It's better to use lsof

while ! lsof -iTCP:9393 -sTCP:LISTEN >/dev/null; do
    echo "server not ready... waiting..."
    sleep 2
done

1 Comment

One command instead of 3. Lower usage of resources, faster run time, easier to read by humans.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.