How to Keep Commands Running After Exiting the Terminal Using nohup in Linux

When you start a long-running script (like a massive database backup or a complex file download) in a Linux terminal, that process is securely attached to your current shell session. If your SSH connection drops, your VPN disconnects, or you simply close the terminal window, the shell will immediately send a SIGHUP (hangup) signal to the script, terminating it instantly. To prevent this and ensure a critical job finishes regardless of your connection status, you must use the nohup command.

How the nohup Command Works

The nohup (no hangup) utility acts as a protective wrapper. When you launch a program using this command, it actively intercepts and ignores the SIGHUP signal sent by the terminal when it closes, allowing the process to continue running silently in the background of the server.

To use it, you simply type nohup followed by the command or script you wish to execute.

nohup ./massive_backup_script.sh

Because the process is now immune to terminal hangups, you can safely close your SSH client or turn off your computer. The script will continue executing on the server until it finishes.

Handling Background Execution and Output

When you run a command with nohup, it still occupies your current terminal prompt until it finishes. If you want to detach it immediately so you can continue using the terminal for other tasks, you must append an ampersand (&) to the very end of the command line. This tells bash to launch the protected process in the background.

nohup ./massive_backup_script.sh &

The terminal will instantly return a process ID (PID) number and give you your prompt back.

However, because the program is now running in the background and detached from your screen, any text it tries to print (like progress updates or error messages) has nowhere to go. By default, the nohup command solves this by automatically creating a new text file named nohup.out in the directory where you launched the command. It redirects all the standard output and error messages into this file.

You can monitor the progress of your hidden script by reading this output file in real-time using the tail command:

tail -f nohup.out

If you prefer to save the log data to a specifically named file rather than the default nohup.out, you can use standard bash redirection operators:

nohup ./massive_backup_script.sh > backup_log_january.txt 2>&1 &

This command safely runs the script in the background, ignores hangups, and routes all output and errors directly into backup_log_january.txt.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.