Can anyone suggest how I might get this working....
I have an R script that takes several minutes to run and writes a few hundred lines of output. I want to write a shell script wrapper around this R script which will launch the R script in the background, pipe its output to a file and start following the bottom of that file. If the user then enters CTRL-C I want that to kill the shell script and tail command but not the R script. Sounds simple right?
I've produced a simplified example below, but I don't understand why this doesn't work. Whenever I kill the shell script the R script is also killed despite apparently running in the background. I've tried nohup, disown etc with no success.
example.R
for(i in 1:1000){
Sys.sleep(1)
print(i)
}
wrapper.sh
#!/bin/bash
Rscript example.R > logfile &
tail -f logfile
Thanks in advance!
Use Rscript to run R from bash You can run it using Rscript test. r . And even better, if you add an initial shebang line #!/usr/bin/env Rscript in the script above and make it executable with chmod +x test. r , you can directly launch your R script with ./test.
To run an R command, put the cursor on the line of the command and then click the Run button at the top of the file window. Or just press CTRL-Enter.
Starting R If R has been installed properly, simply entering R on the command line of a terminal should start the program. In Windows, the program is typically specified as the action performed when clicking on an icon.
The following seems to work on my Ubuntu machine:
#!/bin/bash
setsid Rscript example.R > logfile.txt &
tail -f logfile.txt
Here are some of the relevant processes before sending SIGINT
to wrapper.sh
:
5361 pts/10 00:00:00 bash
6994 ? 00:00:02 update-notifier
8519 pts/4 00:00:00 wrapper.sh
8520 ? 00:00:00 R
8521 pts/4 00:00:00 tail
and after Ctrl+C
, you can see that R
is still running, but wrapper.sh
and tail
have been killed:
5361 pts/10 00:00:00 bash
6994 ? 00:00:02 update-notifier
8520 ? 00:00:00 R
Although appending your Rscript [...]
command with &
will send it to the background, it is still part of the same process group, and therefore receives SIGINT
as well.
I'm not sure if it was your intention, but since you are calling tail -f
, if not interrupted with Ctrl+c
, your shell that is running wrapper.sh
will continue to hang even after the R process completes. If you want to avoid this, the following should work,
#!/bin/bash
setsid Rscript example.R > logfile.txt &
tail --pid="$!" -f logfile.txt
where "$!"
is the process id of the last background process executed (the Rscript [...]
call).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With