3

I am running an R script via bash script and want to return the output of the R script to the bash script to keep working with it there.

The bash is sth like this:

#!/bin/bash
Rscript MYRScript.R
a=OUTPUT_FROM_MYRScript.R
do sth with a

and the R script is sth like this:

for(i in 1:5){
i
sink(type="message")
}

I want bash to work with one variable from R at the time, meaning: bash receives i=1 and works with that, when that task is done, receives i=2 and so on.

Any ideas how to do that?

3
  • you want to construct a pipe from your running R-script to another shell-command. is it right? Commented Oct 27, 2015 at 15:06
  • Yes, but from R to unix, not unix to R Commented Oct 27, 2015 at 15:09
  • I want to use the R output (a filename) to be directly used in bash to modify another file there. Seems to me to be easier this way... ? Commented Oct 27, 2015 at 15:16

2 Answers 2

3

One option is to make your R script executable with #!/usr/bin/env Rscript (setting the executable bit; e.g. chmod 0755 myrscript.r, chmod +x myrscript.r, etc...), and just treat it like any other command, e.g. assigning the results to an array variable below:

myrscript.r

#!/usr/bin/env Rscript
cat(1:5, sep = "\n")

mybashscript.sh

#!/bin/bash
RES=($(./myrscript.r))
for elem in "${RES[@]}"
do
  echo elem is "${elem}"
done

nrussell$ ./mybashscript.sh
elem is 1
elem is 2
elem is 3
elem is 4
elem is 5
Sign up to request clarification or add additional context in comments.

4 Comments

strangely enough I get a Permission denied (for myrscript.r) error when running your solution. Any ideas why?
Do a chmod 0755 myrscript.r first,
@gugy Sorry I kind of glossed over that in my answer; thank you Dirk.
How to prevent printing of R startup intro in output?
0

Here is MYRScript.R:

for(iter in 1:5) {
  cat(iter, ' ')
}

and here is your bash script:

#!/bin/bash

r_output=`Rscript ~/MYRscript.R`

for iter in `echo $r_output`
do
    echo Here is some output from R: $iter
done

Here is some output from R: 1
Here is some output from R: 2
Here is some output from R: 3
Here is some output from R: 4
Here is some output from R: 5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.