When you run a command with nohup
, it automatically redirects both stdout and stderr to nohup.out
. This is problematic when:
- You want real-time monitoring of the output
- You need to see logs immediately while keeping the process running
- You're debugging a long-running process
The proper way to handle this is by explicitly managing the output streams:
nohup python start.py > /dev/tty 2>&1 &
This command:
- Redirects stdout to the terminal (
/dev/tty
) - Redirects stderr to stdout (
2>&1
) - Still keeps the process running in background (
&
)
If you need BOTH terminal output AND logging to a file:
nohup python start.py 2>&1 | tee nohup.out &
Key points about this approach:
2>&1
merges stderr with stdouttee
writes to both terminal and file- The final
&
backgrounds the entire pipeline
If you're on a modern Linux system, consider using systemd instead:
# Create a service unit
echo "[Service]
ExecStart=/usr/bin/python /path/to/start.py
Restart=always
StandardOutput=journal+console
StandardError=journal+console" > /etc/systemd/system/myservice.service
# Then enable and start
systemctl enable myservice
systemctl start myservice
Remember that:
- Terminal output might be lost if you log out (depending on your terminal manager)
- For true persistence, consider using
screen
ortmux
- The process will still be killed if the system reboots
When running long-term processes on Linux servers, many developers use nohup
to prevent the process from terminating when the SSH session ends. By default, nohup
redirects both stdout and stderr to nohup.out
, which can be problematic when you need real-time output monitoring.
The simplest solution is to explicitly redirect output streams while using nohup:
nohup python start.py > /dev/tty 2>&1 &
This command:
- Redirects stdout to the terminal (
/dev/tty
) - Redirects stderr to stdout (
2>&1
) - Runs in background (
&
)
For more complex scenarios where you want both screen output and logging:
nohup python start.py 2>&1 | tee -a output.log &
This approach:
- Combines stdout and stderr (
2>&1
) - Pipes to
tee
which shows output and logs to file - Appends (
-a
) to preserve existing log content
For more robust session management, consider terminal multiplexers:
# Using tmux
tmux new -s mysession
python start.py
# Detach with Ctrl+B D
Benefits include:
- Persistent sessions that survive disconnections
- Full terminal emulation
- Ability to reattach later
When redirecting nohup output, watch for:
- Permission errors with
/dev/tty
- Buffering issues (use
stdbuf -oL
for line buffering) - Terminal compatibility problems