2

I want to create a Shell script (.sh) using MacOS and LinuxOS (respectively). This is what I have made:

#!/bin/bash

redis-server &
mongod &
cd ~/some/path && npm start &
cd ~/some/path && ./ngrok http 3000 -region=eu &

echo "My Workspace has been started"

I want redis-server to be running in background, and only by the time that the redis-server was fully initiated I want then to run the mongod service. And so for and so on.

At the end of the script I want to see the My Workspace has been started log on the Terminal.

What happens now is that it runs all of them together, I can see mixin logs in the Terminal of the redis, and then of the mongo and then some from the npm and etc.

How can I achieve this?

1 Answer 1

2

You should wait for the previous command's successful execution I assume. That can be achieved like:

#!/bin/bash

redis-server && \
    mongod &&\
    cd ~/some/path && npm start &&\
    cd ~/some/path && ./ngrok http 3000 -region=eu &&\    
    echo "My Workspace has been started"

This way every command depends on the previous one's execution. However if any of them` are not set up to exit after execution (which is very likely since the first two are services) it will never be finished properly.

So to solve this You can create some checks for running services, like:

#!/bin/bash

redis-server &
sleep $SOMEMINUTES &&\
ps WHATEVEROPTIONSYOUPREFER | grep redis && \
mongod &

You see the pattern here. Or You can rely on this for redis:

#!/bin/bash

redis-server &
sleep $SOMEREASONABLETIME && redis-cli ping && \
mongod &
cd ~/some/path && npm start &
cd ~/some/path && ./ngrok http 3000 -region=eu &

echo "My Workspace has been started"

For mongodb You might have to rely on ps or netcat to check the status as far as I know. Here You can find some examples.

Sign up to request clarification or add additional context in comments.

3 Comments

Fun fact: the \ behind && is not needed. You can just end commands with && + <newline>, without \ . The newlines and comment lines are ignored after && or || or | etc.
You could use until and pgrep redis instead of the sleep and ps. That way it would keep looking until it starts. Like this : until pgrep redis; do sleep 1; done
Thanks @KamilCuk I newer knew that!

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.