Difference between nohup and &(ampersand) in linux ?

In this post we will look at the difference between nohup and &(ampersand) in Linux.

As we know & (ampersand) is used to send any command execution to background and similar task is performed by nohup command.

However most of us don’t know the difference between the two.

Hence in this post we will look at their differences and how to change nohup command behavior.

Sending Command Execution to background

1. Using & Command

### Run a loop to print "hello" every 15 seconds.
[root@ngelinux ~]# while true; do echo "hello" > /dev/pts/0; sleep 15; done &
[1] 8563
[root@ngelinux ~]# hello

2. Using nohup command

[root@ngelinux ~]# nohup `while true; do echo "hello" > /dev/pts/0; sleep 15; done` &
[2] 8576
[root@ngelinux ~]# hello

3. Viewing current running jobs

[root@ngelinux ~]# jobs -l
[1]-  8563 Running                 while true; do echo "hello" > /dev/pts/0; sleep 15; done &
[2]+  8576 Running                 nohup `while true; do echo "hello" > /dev/pts/0; sleep 15; done` &
[root@ngelinux ~]# 

Behavior of & and nohup

In the above example, we can see using & and nohup performs similar task by sending the command to background.

Difference between nohup and &

nohup and & performs the same task.

When we exit the terminal/shell, the process started with & receives the Hang UP(HUP) signal and the shell processes gets killed.

To prevent this situation, we can use nohup command which ideally ignores the HUP signal.

nohup command catches the hangup signal (do man 7 signal for help) whereas the ampersand/& doesn’t.

When we run a command using & and exit the shell afterwards, the shell will kill the sub-command with the hangup(SIGHUP) signal (kill -SIGHUP).

nohup can prevent this situation as it catches the signal and ignores it so that it never touches the actual application.

Check NoHUP signal Setting on Bash Shell

In case of bash shell, we can use shopt command and grep hupon to find out whether our shell sends SIGHUP signal to its child processes or not.

If it is off, processes will not be terminated. In case its on, it works similar to ampersand command.

### Check if hup is on or off
### Since its off, the hup signal is ignored, and hence process is not killed
[root@ngelinux ~]# shopt | grep -i hup
huponexit      	off
[root@ngelinux ~]# 

Turning on huponexit to disable nohup command feature

We can also turn off huponexit so that it accepts HUP signal on parent process termination and hence it will work similar to ampersand in this case.

### huponexit default value
[root@ngelinux ~]# shopt huponexit
huponexit      	off

### Toggle huponexit value using -s option
[root@ngelinux ~]# shopt -s huponexit

### huponexit is turned on
[root@ngelinux ~]# shopt huponexit
huponexit      	on
[root@ngelinux ~]# 

I hope you liked the article.

Do post your valuable comments below.

3.5 2 votes
Article Rating
Notify of

Inline Feedbacks
View all comments