Reputation: 67310
I have 4 commands I want to run:
sudo mkdir -p /data/db && \
sudo chmod 755 /data/db && \
sudo chown -R addison.pan: /data && \
mongod &
I only want to run mongod in the background if the other 3 above it succeed. But when I type this into bash, it runs the whole thing as one background task. How do I only make the mongod
run in the background, and only if it gets to it?
Upvotes: 3
Views: 86
Reputation: 212208
Be explicit. There's no need to try to abuse the syntax to use a short-circuit:
if \
sudo mkdir -p /data/db \
&& sudo chmod 755 /data/db \
&& sudo chown -R addison.pan: /data
then
mongod &
fi
Upvotes: 2
Reputation: 32279
To run one or more commands in a separate process, enclose that series of commands in parentheses. As specified in the Single Unix Specification, §2.9.4 “Compound Commands”:
( compound-list )
Execute compound-list in a subshell environment […]
To group one or more commands in the same shell process, enclose that series of commands in curly braces:
{ compound-list ; }
Execute compound-list in the current process environment. […]
That's true for any POSIX shell (so it also works in Bash).
So your example can be changed to:
sudo mkdir -p /data/db && \
sudo chmod 755 /data/db && \
sudo chown -R addison.pan: /data && \
( mongod & )
That may be good because you want the mongod
process separated. On the other hand, a more general answer would be to group the list of commands within the same shell process:
sudo mkdir -p /data/db && \
sudo chmod 755 /data/db && \
sudo chown -R addison.pan: /data && \
{ mongod & }
Both these are described in the above documentation references.
Upvotes: 3
Reputation: 26905
You could run multiple commands within sudo
, for example:
sudo sh -c 'mkdir -p /data/db && chmod 755 /data/db && chown -R <user>: /data' \
&& mongod &
Upvotes: 0
Reputation: 64672
Use parens:
sudo mkdir -p /data/db && \
sudo chmod 755 /data/db && \
sudo chown -R addison.pan: /data && \
(mongod &)
Upvotes: 0