How to run background command with nohup

remarkablemark
1 min readApr 3, 2022

--

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 redis.conf >/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:

Demo

Replit:

--

--