Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

run a shell script and immediately background it, however keep the ability to inspect its output

How can I run a shell script and immediately background it, however keep the ability to inspect its output any time by tailing /tmp/output.txt.

It would be nice if I can foreground the process too later.


P.S.

It would be really cool if you can also show me how to "send" the backgrounded process in to a GNU screen that may or may not have been initialized.

like image 505
american-ninja-warrior Avatar asked May 28 '17 00:05

american-ninja-warrior


People also ask

How do I keep a shell script running in the background?

Running shell command or script in background using nohup command. Another way you can run a command in the background is using the nohup command. The nohup command, short for no hang up, is a command that keeps a process running even after exiting the shell.

How do I run a running script in the background?

Use bg to Send Running Commands to the Background You can easily send these commands to the background by hitting the Ctrl + Z keys and then using the bg command. Ctrl + Z stops the running process, and bg takes it to the background.

How do you run a process in the background in Unix shell script?

A script can be run in the background by adding a "&" to the end of the script. You should really decide what you want to do with any output from the script. It makes sense to either throw it away, or catch it in a logfile. If you capture it in a log file, you can keep an eye on it by tailing the log file.

How do I run a bash shell in the background?

Nohup, with & and /dev/null nohup bypasses the HUP signal (signal hang up), making it possible to run commands in the background even when the terminal is off. Combine this command with redirection to “/dev/null” (to prevent nohup from making a nohup. out file), and everything goes to the background with one command.


1 Answers

To 'background' a process when you start it

Simply add an ampersand (&) after the command.

If the program writes to standard out, it will still write to your console / terminal.


To foreground the process

Simply use the fg command. You can see a list of jobs in the background with jobs.

For example:

sh -c 'sleep 3 && echo I just woke up' & jobs


To background a currently running process

If you have already started the process in the foreground, but you want to move it to the background, you can do the following:

  1. Press Ctrl+z to put the current process to sleep and return to your shell. This process will be paused until you send it another signal.
  2. Run the bg command to resume the process, but have it run in the background instead of the foreground.
like image 182
Jon Wolski Avatar answered Sep 28 '22 02:09

Jon Wolski