Generate and execute R, Python, etc., a script from a bash script

I tried to find a solution for this for a while, but so far have not found anything satisfactory. I write a lot of bash scripts, but sometimes I want to use R or Python as part of a script. Right now I have to write two scripts; the original bash script to complete the first half of the task, and the R or Python script to complete the second half of the task. I am calling an R / Python script from a bash script.

I am not satisfied with this solution because it splits my program into two files, which increases the likelihood of exiting synchronization, more files to track, etc. Is there a way to write a block of text that contains my entire R / Python script and then bash spit it out into a file and pass arguments to it and execute it? Is there an easier solution? This is more complicated than porting simple single-line to R / Python, since it usually involves creating and managing objects in stages.

+4
source share
2 answers

There are probably many solutions, but this works:

#!/bin/bash
## do stuff
R --slave <<EOF
  ## R code
  set.seed(101)
  rnorm($1)
EOF

If you need the flexibility to pass additional bash arguments to R, I suggest:

#!/bin/bash
## do stuff
R --slave --args $@ <<EOF
  ## R code
  set.seed(101)
  args <- as.numeric(commandArgs(trailingOnly=TRUE))
  do.call(rnorm,as.list(args))
EOF
  • , ,
  • , bash script R sub script

, , .

+7

python, Ben Bolker.

#!/bin/bash
python << EOF
print 'Hello $1'
EOF

:

> sh test.sh "world"

Hello world

-----------------------------------------------

bash python:

for ((i=1;i<=$1;i++)) do
python << EOF
print 'Hello world $i times'
EOF
done

:

> sh test.sh 5

Hello world 1 times
Hello world 2 times
Hello world 3 times
Hello world 4 times
Hello world 5 times

pandas, numpy, matplotlib .

+6

Source: https://habr.com/ru/post/1616289/


All Articles