Bring nohup job to foreground
Consider the following nohup
execution:
nohup script.sh > script.out &
Is there a way to log off the terminal, reconnect, bring the process back to foreground and interact with it using the keyboard?
Solution 1:
nohup does not disconnect a command from terminal, it makes your script ignore SIGHUP
, and redirects stdout/stderr
to a file nohup.out
, so that the command can continue running in the background after you log out.
nohup
does not automatically put the command it runs in the background. One must do that explicitly, by ending the command line with an &
.
$ nohup ./script.sh &
[1] 3390
$ nohup: ignoring input and appending output to ‘nohup.out’
jobs
can print currently running jobs and their status. If the command jobs
cannot find it, then it is no longer a child process of that shell.
$ jobs
[1]+ Running nohup ./script.sh &
One can be bring back a background job to foreground in bash using fg
even if it is run with nohup
. But that won't change the output redirection, which will still be going to the file nohup.out
.
$ fg
nohup ./script.sh
If you close the shell/terminal or log off, your command is no longer a child of that shell. It belongs to init
process. If you search in pstree
you'll see it is now owned by process 1 (init
). That cannot be brought back to the foreground because the foreground no longer exists.
Solution 2:
If you wanted to start a script, have it run without the output bothering your terminal and then bring it up later to interact with it, you might want to take a look at a terminal multiplexer. Depending on your system I would recommend tmux
or screen
. You can find some info on how to use them in the links below:
tmux:
- A Tmux Primer
- A Quick and Easy Guide to tmux
- Tmux Cheat Sheet & Quick Reference
screen:
- Screen - Community Ubuntu Documentation
- GNU Screen: an introduction and beginner's tutorial
- screen keyboard shortcuts
edit: added links for tmux primers