Innovate | Connect | Transform
ContactService statusUSD $

GICT knowledge base

How to Use the nohup Command in Bash

Published

LinuxLinux and Commands

If you’ve ever spent time working on a Linux server especially over SSH chances are you’ve worried about what happens if your connection drops or your terminal closes. Maybe you started a long-running process, like a database migration, video encoding, or data backup, only to realize you can’t babysit your terminal the entire time. Or perhaps you’ve lost an SSH connection mid-task and found your process killed, leaving you to start over.

That’s where the nohup command comes in. Short for “no hang up,” nohup is a little utility with big impact. It lets you run commands that keep going even after you log out or close your terminal. It’s a classic Unix tool that’s stood the test of time, and while there are more modern alternatives, it’s still found everywhere and is incredibly useful.

In this article, we’ll dive deep into what nohup does, how to use it, common pitfalls, best practices, and even some advanced tricks. Along the way, I’ll share real-world stories and context to help you not just use nohup, but really understand why and when it shines.

What is nohup?

Let’s start with the basics: what is nohup, and why do you need it?

On Unix and Linux systems, every terminal session has an associated controlling terminal and processes inherit this association. When you close your terminal or log out, the system sends a “hangup” signal (SIGHUP) to all jobs started from that session. By default, this signal terminates those jobs. So any script, command, or process you start from a terminal will die when your session ends unless you take steps to prevent it.

nohup solves this problem. It works by telling the system to ignore the SIGHUP signal for the command you run. In plain English: “Don’t kill this command if the session hangs up or I log out.”

Why Use nohup? Practical Scenarios

Let’s look at some classic use cases where nohup is a lifesaver.

  • Running Long Tasks Over SSH: Suppose you SSH into a remote server to start a big data backup or run a script that takes hours. You don’t want to leave your laptop plugged in and connected the whole time. With nohup, you can start the job, disconnect, and know it’ll keep running.
  • Avoiding Accidental Shutdowns: Ever had your terminal freeze or close unexpectedly? With nohup, you don’t have to worry about losing hours of processing because your terminal died.
  • Starting Background Services: You might want to start a web server, API, or other service as a background process, without tying it to your current session.
  • Running Scripts During Maintenance Windows: Start a task late at night, log out, and go to bed your process will keep chugging along until it’s done.

The Basics: How to Use nohup

The simplest way to use nohup is:

nohup command &

Let’s break it down:

  • nohup: Tells the system to ignore hangup signals for this command.
  • command: The command or script you want to run.
  • &: Runs the command in the background, so you get your terminal prompt back.

By default, all output (stdout and stderr) is redirected to nohup.out in your current directory.

A Simple Example

Suppose you want to run a Python script that processes a huge dataset:

nohup python3 big_data_script.py &

You’ll see a message like:

appending output to nohup.out

Now you can log out, close your terminal, or lose your SSH connection, and the script keeps running.

Where Does the Output Go?

By default, nohup redirects both standard output (stdout) and standard error (stderr) to nohup.out in your current working directory. If it can’t create the file there, it tries your home directory.

If you want to specify your own output file, use shell redirection:

nohup command > mylog.txt 2>&1 &

This sends both stdout and stderr to mylog.txt. If you only care about stdout and want to discard errors, you could do:

nohup command > mylog.txt 2>/dev/null &

How Does nohup Work Behind the Scenes?

Here’s what happens when you use nohup:

  • It starts your command with SIGHUP (signal 1) ignored.
  • It redirects stdout and stderr to nohup.out (or wherever you specify).
  • The command runs as a child process, independent of your terminal.
  • If you close your terminal or log out, the process continues running.

This is possible because SIGHUP is a signal sent to all processes associated with a terminal when it closes. By ignoring it, nohup prevents your command from being killed by this event.

Best Practices for Using nohup

  • Use Output Redirection Thoughtfully: Always specify your output file when possible, especially for long-running or important jobs:
    nohup ./my_script.sh > /var/log/my_script.log 2>&1 &

    This makes it easier to find your logs and avoid clutter.

  • Name Your Jobs and Keep Track of PIDs: When you start a job with nohup, it runs in the background and the shell prints its process ID (PID). For example:
    [1] 12345

    You can check on your job later with:

    ps -p 12345

    Or, to get a list of all jobs started by your user:

    ps -u $USER | grep my_script
  • Use Scripts for Complex Tasks: If your job involves multiple commands, write a Bash script and run that with nohup. This helps with debugging and organization.Example:
    #!/bin/bash
    date
    echo "Starting big job"
    python3 big_data_script.py
    date
    echo "Done!"

    Run:

    nohup ./batch_job.sh > batch_job.log 2>&1 &

Real-World Story: The Nightly Database Import

Years ago, I worked at a company that had to import huge CSV data dumps every night. The script took several hours, and if anyone lost their SSH connection, it had to be started over from scratch. After a few disasters, we switched to:

nohup ./import_data.sh > import.log 2>&1 &

Suddenly, no one had to babysit the script. If something went wrong, we could check import.log the next morning. It saved us countless hours and headaches.

Checking on Your Backgrounded nohup Job

Once your job is running in the background, how do you check on it?

  1. Tail the Output File: If you logged output to a file, use tail to watch progress:
    tail -f nohup.out

    or

    tail -f mylog.txt
  2. Check the Process Status: Use ps to see if it’s still running:
    ps -p <PID>

    Or search for the command:

    ps aux | grep my_script
  3. Use jobs (if you started it in the current shell):
    jobs -l

Stopping a nohup Process

To stop a backgrounded process, use kill with its PID:

kill 12345

If the process ignores SIGTERM, use:

kill -9 12345

But beware: kill -9 is forceful and should be used as a last resort.

Common Pitfalls and How to Avoid Them

  • Forgetting the Ampersand (&): If you don’t add &, the command runs in the foreground, and your terminal will wait for it to finish before returning the prompt.
    nohup my_script.sh &
  • Not Redirecting Output: By default, all output goes to nohup.out, which can get huge and hard to find. Always redirect output to a named file for clarity.
  • Overwriting vs. Appending Output: Using > overwrites files. If you want to append:
    nohup my_script.sh >> mylog.txt 2>&1 &
  • Running Interactive Commands: nohup is best for commands that don’t need user input. If your command expects interaction, it’ll hang waiting for input that will never come.

Comparing nohup to Other Tools

screen and tmux

nohup is straightforward, but sometimes you want to detach and reattach to a running session. That’s where screen and tmux shine. They create persistent terminal sessions you can reconnect to later.

Example with tmux:

tmux
# Start your command
python3 long_running_task.py
# Detach: Press Ctrl+B, then D
# You can close your terminal or disconnect
# Reattach later with:
tmux attach

disown (a Bash built-in)

If you forgot to start a command with nohup, you can use disown to remove it from the shell’s job table so it won’t get killed on logout.

./my_script.sh &
disown

For even more robustness, send SIGHUP to be ignored:

trap '' SIGHUP

Advanced Usage

Starting Multiple Jobs

You can run multiple jobs with nohup:

nohup ./job1.sh > job1.log 2>&1 &
nohup ./job2.sh > job2.log 2>&1 &

Keep note of each job’s PID to manage them later.

Chaining Commands

You can run a whole pipeline or a compound command with nohup by using a subshell:

nohup bash -c 'python3 script1.py && python3 script2.py' > combined.log 2>&1 &

Using nohup with Crontab

For scheduled tasks, it’s usually not necessary, as cron jobs are disconnected from any terminal by default. However, if you ever need to ensure a job won’t stop even if cron dies (rare), you could combine the two.

Security and Permissions Considerations

Log Files: Make sure your log files are stored securely and with appropriate permissions, especially if sensitive information could be logged.

Resource Limits: Background jobs can still consume system resources. Monitor disk space and CPU usage, especially on multi-user or production systems.

Zombie Processes: Always check that your jobs finish cleanly and don’t leave orphaned or zombie processes.

Troubleshooting Tips

Problem: “nohup: failed to run command: No such file or directory”

Check that your command or script exists and is executable. Use absolute paths for reliability.

Problem: Output Not Written to File

Double-check your output redirection syntax and file permissions.

Problem: Process Dies Anyway

Some scripts explicitly call exit or handle signals in a way that still kills the process. Review your script for signal handling or use alternative tools (screen, tmux) if needed.

Environment Variables and nohup

If your background job depends on environment variables (like PATH, PYTHONPATH, or custom config), make sure they’re set before running nohup, or specify them inline:

export API_KEY=abcdef nohup ./app.sh > app.log 2>&1 &

Or:

nohup env API_KEY=abcdef ./app.sh > app.log 2>&1 &

Cleaning Up After nohup

When your job is done, don’t forget to clean up:

  • Check log files: Review and archive or delete them to save space.
  • Remove temp files: If your job creates temporary files, make sure they’re cleaned up by your script (use trap in Bash).
  • Stop jobs you no longer need: Kill or terminate jobs that are no longer required.

Real-World Story: The Mistaken Job

Once, I started a long-running job with nohup, but forgot to redirect output. The nohup.out file grew to several gigabytes, eventually filling up the disk and causing other jobs to fail. Lesson learned: always specify your own log file and monitor disk usage!

FAQ

Can I use nohup for GUI applications?
Generally, no. GUI apps expect a display and user interaction. nohup is for command-line tasks.

What happens to processes started with nohup after a reboot?
They will be killed unless explicitly restarted by a boot script, cron job, or a process supervisor like systemd.

Can I get my shell prompt back after running nohup in the foreground?
If you forgot to start nohup with &, press Ctrl+Z to suspend, then type bg to send it to the background. After that, use disown to detach it from the shell.

Conclusion

The nohup command is a classic Unix tool that’s as useful today as it was decades ago. Whether you’re running big data jobs, starting services, or just want to keep your work alive after you log out, nohup is simple, portable, and effective.

Remember the basics: always use & to run in the background, redirect your output to a log file you control, and keep track of your process IDs. For more advanced needs, tools like screen and tmux offer even more flexibility, but nohup remains a trusty workhorse for many use cases.

So the next time you’re planning to run something big, long, or important on a Linux box don’t risk losing your progress to a dropped session. Reach for nohup, and keep your work running, no matter what.

Related guides

Account services are unavailable until the production backend is configured.