This article goes over how to run a command in the background with nohup.
Problem
Imagine you’re creating a script that runs redis-server
then redis-cli
:
redis-server
redis-cli
redis-cli
never starts since redis-server
runs forever.
Solution
One solution is to run redis-server
in the background with &
:
redis-server &
However, to run redis-server
with no hang up, use nohup
:
nohup redis-server &
The output of redis-server
is saved to nohup.out
:
cat nohup.out
To pass the argument redis.conf
to redis-server
:
nohup redis-server redis.conf &
To silence the nohup output in the command-line:
nohup redis-server >/dev/null 2>&1 &
Now you can run redis-server
and redis-cli
in the same script:
nohup redis-server &
redis-cli
But one problem is that redis-server
never shuts down.
Thus, save the pid:
nohup redis-server &
echo $! > /tmp/redis-server.pid
And kill it before it runs (if applicable):
kill $(cat /tmp/redis-server.pid)
Script
Working example script:
# shut down redis-server (if applicable)
REDIS_SERVER_PID_FILE=/tmp/redis-server.pid
(kill $(cat $REDIS_SERVER_PID_FILE) 2>&1) >/dev/null
sleep 0.1
# start redis-server
nohup redis-server redis.conf >/dev/null 2>&1 &
sleep 0.1
echo $! > $REDIS_SERVER_PID_FILE
# start redis-cli
redis-cli