What is the nohup command?

Overview

Every Linux command begins a process at the moment of its execution, which is terminated when the terminal is closed. If you’re running applications through SSH and the connection stops, the session will be terminated, and all running processes will halt.

In certain situations, executing actions in the background may be extremely beneficial to the user, which is where the nohup command comes into play. In Linux systems, nohup (No Hang Up) is a command that keeps the process running even after you log out of the shell/terminal.

When a process is started with the nohup command, the command loses access to stdin, and the nohup.out file is used as the default stdout and stderr file. The output of the process started with the nohup command can be redirected to a different file for stdout and stderr.

Using nohup to start a process

Syntax:

nohup command command-arguments [> output_file.txt]
  • command: This is the process that has to be executed.
  • command-arguments: These are the arguments applicable to the command.
  • [> output_file.txt]: The output of the command can be redirected to a different file using the > symbol followed by the filename.

Example

In the code below, we create a bash script called script.sh that prints the process start and end time. Upon running the nohup command in the main.sh file, the nohup.out file is created in the directory where the nohup command is executed.

main.sh
script.sh
nohup bash script.sh

The code below shows that we can run multiple commands using nohup and the output will be redirected to the nohup_output.txt file.

nohup bash -c 'date && ls -l' > nohup_output.txt

Free Resources