Open In App

nohup Command in Linux with Examples

Improve
Improve
Like Article
Like
Save
Share
Report

Every command in Linux starts a process at the time of its execution, which automatically gets terminated upon exiting the terminal. Suppose, you are executing programs over SSH and if the connection drops, the session will be terminated, all the executed processes will stop, and you may face a huge accidental crisis. In such cases, running commands in the background can be very helpful to the user and this is where nohup command comes into the picture. nohup (No Hang Up) is a command in Linux systems that runs the process even after logging out from the shell/terminal. 

Usually, every process in Linux systems is sent a SIGHUP (Signal Hang UP) which is responsible for terminating the process after closing/exiting the terminal. Nohup command prevents the process from receiving this signal upon closing or exiting the terminal/shell. Once a job is started or executed using the nohup command, stdin will not be available to the user and nohup.out file is used as the default file for stdout and stderr. If the output of the nohup command is redirected to some other file, nohup.out file is not generated. 

Syntax:

nohup command [command-argument ...]

Working with nohup command

1. Checking the version of Nohup:

The version of nohup command can be checked by using the following command.

$ nohup --version

Output:

nohup version

2. To run a command in the foreground:

Runs the command in the foreground and redirects the command output to the nohup.out file if any redirecting filename is not mentioned.

$ nohup bash geekfile.sh

Output:

nohub bash

To redirect the output to the output.txt file:

$ nohup bash geekfile.sh > output.txt

Output:

nohu bash output.txt

3. To run a command in the background (with ‘&’): 

To run the command in the background, the ‘&’ symbol is appended at the end of the command. After executing, it doesn’t return to the shell command prompt after running the command in the background. It can be brought back to the foreground with the fg command.

$ nohup bash geekfile.sh &
fg

Output:

nohup bash script

Note: The number within square brackets represents the job id and the number next to it is the process id.

4. To run multiple commands in the background:

nohup command can be used to run multiple commands in the background.

$ nohup bash -c 'commands'

Example:

$ nohup bash -c 'cal && ls'

Output:

To run multiple commands in the background:

Here, the output will be by default stored in nohup.out. To redirect it, type:

$ nohup bash -c 'commands' > filename.txt

Example:

$ nohup bash -c 'cal && ls' > output.txt

Output:

Storing the output in output file


Last Updated : 02 Dec, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads