What is nohup in Linux?

A terminal has been attached to the end of this shot. You can try out the commands used in the shot in this terminal.

When we execute a command in Linux, it creates our process in the background and assigns a unique process ID. This process can end in three ways:

  1. The task assigned is completed.
  2. You kill the process explicitly.
  3. You log off, or in the case of SSH, the connection drops, and the session is terminated.

Imagine you run a critical process, and you need to log off urgently or the connection drops. The process stops immediately, and you might lose your work.

To avoid this, we can use the nohup command. nohup in Linux executes other commands specified in the arguments. This command ignores all SIGHUPhangup signals. SIGHUP is sent to a process when its controlling terminal is closed.

To understand better, let’s see the syntax:

nohup COMMAND [ARGS]

Run command in the foreground

The nohup will run in the foreground, and the output of the command will be stored in the nohup.out file. The nohup command will create this file in the current directory. If the user doesn’t have sufficient permissions to write a file in the current directory, nohup will generate the output file in the home directory.

Let’s look at an example output below.

root@educative:/# MYCOMMAND="echo 'My name is Kedar.'"

root@educative:/# nohup $MYCOMMAND
nohup: ignoring input and appending output to 'nohup.out'

When we cat the contents of the output file, we see this:

root@educative:/# cat nohup.out 
'My name is Kedar'

We used a small command, so it executes immediately. For an extensive process, you can log out at this point, and the process will still run.

Run command in the background

We can also run this command in the background. To run it in the background, we use the & operator.

If we run the same command in the background, we get the following output.

root@educative:/# MYCOMMAND="echo 'My name is Kedar.'"
root@educative:/# nohup $MYCOMMAND &
[1] 24
root@educative:/# nohup: ignoring input and appending output to 'nohup.out'

The integer you see in the output is a process ID.

You can also kill this background process with the process ID:

kill -9 24

That’s all for this shot! Hopefully, you now have some idea of how to use the nohup command.

Happy learning.

Terminal 1
Terminal
Loading...

Free Resources

Attributions:
  1. undefined by undefined