I wrote a small R script to read JSON, which works fine but upon piping with
Rscript myscript.R | head
the (full, expected) output comes ba
The error is simply caused by an attempt to write to the pipe without a process connected to the other end. In other words, your script has already picked up and left by the time the pipe is reached and the HEAD
command is called.
The command itself might not be the issue; it could be something within the script causing an early termination or race condition before reaching the pipe. Since you're getting full output it may not be that much of a concern, however, masking the error with other CLI
commands as mentioned probably isn't the best approach.
The command line solution:
R
does have a couple of useful commands for dealing with instances in which you might want the interpreter to wait, or perhaps suppress any errors that would normally be output to stderr.
For command-line R, error messages written to ‘stderr’ will be sent to the terminal unless
ignore.stderr = TRUE
. They can be captured (in the most likely shells) by:
system("some command 2>&1", intern = TRUE)
There is also the wait
argument which could help with keeping the process alive.
wait
— logical (not NA) indicating whether the R interpreter should wait for the command to finish, or run it asynchronously. This will be ignored (and the interpreter will always wait) ifintern = TRUE
.
system("Rscript myscript.R | head 2>&1", intern = TRUE)
The above would wait, and output errors, if any are thrown.
system("Rscript myscript.R | head", intern = FALSE, ignore.stderr = TRUE)
The above won't wait, but would suppress errors, if any.