How to run async commands in queue AND in background?

Viewed 215

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 Answers

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.

Related