0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use nohup in Bash: Run Commands After Logout

Use nohup before a command in bash to run it immune to hangups, allowing it to continue after logout or terminal close. The output is saved to nohup.out by default unless redirected.
📐

Syntax

The basic syntax of nohup is:

  • nohup command [arguments] &

Here:

  • nohup runs the command ignoring hangup signals.
  • command [arguments] is the program and its options you want to run.
  • & runs the command in the background so you can continue using the terminal.
bash
nohup command [arguments] &
💻

Example

This example runs a simple bash script that prints numbers every second. Using nohup lets it keep running after logout.

bash
nohup bash -c 'for i in {1..5}; do echo "Number $i"; sleep 1; done' &
Output
nohup: ignoring input and appending output to 'nohup.out'
⚠️

Common Pitfalls

Common mistakes when using nohup include:

  • Not redirecting output, which goes to nohup.out by default and may clutter your directory.
  • Forgetting the & to run the command in the background, which blocks the terminal.
  • Running commands that require user input, which will hang since nohup ignores input.

Correct usage example with output redirection:

bash
nohup long_running_command > output.log 2>&1 &
Output
nohup: ignoring input and appending output to 'output.log'
📊

Quick Reference

OptionDescription
nohup command &Run command immune to hangups in background
nohup command > file 2>&1 &Run command, redirect all output to file, in background
kill PIDStop the running background process by its PID
jobsList background jobs in current shell
fg %jobBring background job to foreground

Key Takeaways

Use nohup to keep commands running after logout or terminal close.
Add & to run the command in the background and free the terminal.
Redirect output to a file to avoid cluttering nohup.out.
Avoid commands that require interactive input when using nohup.
Check running background jobs with jobs and stop them with kill.