Linux nohup command with examples

In this article, We will see Linux nohup command with examples.

What is nohup?

Linux nohup command keeps processes running even after exiting the shell or terminal. Nohup prevents the processes or jobs from receiving the SIGHUP (Signal Hang UP) signal. This is a signal that is sent to a process upon closing or exiting the terminal. Linux nohup command is used for large scripts execution, database backups, generating huge series,..

Suppose, if we are executing programs over SSH and if the connection drops, the session will be terminated, all the executed processes will stop, and we may face a huge accidental crisis. In such cases, running commands in the background can be very helpful. This can be achieved by using Linux nohup command.

Linux nohup syntax and options:

nohup COMMAND [ARG]...

Options:
–help display this help and exit
–version output version information and exit

Linux nohup command examples:

1. Check the Linux nohup version.

nohup --version

Linux nohup command with examples

2. Lets run simple nohup with other command.

Let’s create file mycommand.sh and add following commands. Enter the commands and press enter then control D to save and quit.

cat > mycommand.sh ls ps cal

Now, grant executable permissions to the file.

chmod a+x mycommand.sh

Run the command mycommand.sh file. It does not receive input. All output, including any error messages, is written to the file nohup.out in the working directory, or in our home directory. If mycommand.sh is running when you log out or close the terminal, mycommand.sh does not terminate.

nohup bash mycommand.sh

Now, run the ls command in the current working directory and verify nohup.out file is there or not. Then, view the contents of nohup.out.

ls
cat nohup.out

3. Run the command in background

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. Later it can be bring back to the foreground using Linux fg command.

nohup bash mycommand.sh &

Where number 9449 is the job id.

We can terminate the job id(process id) by using below command.

kill -9 9449

4. Redirect output to output.txt file but not to nohup.out file.

nohup bash mycommand.sh > output.txt

5. To redirect the standard output and standard error to different files:

nohup bash mycommand.sh > output.txt 2> errors.txt &

We can verify the jobs running in background by nohup using jobs command.

r2schools@PGSlave:~/txtfiles$ jobs [1]+ Done nohup bash mycommand.sh > output.txt 2> errors.txt

So in this article, we have seen nohup command definition, syntax and different examples.