JerryWho
JerryWho

Reputation: 3105

How to run knitr from shell script

I have to run knitr from a shell script. But I messed something up.

My shell script test.sh is:

#!/bin/bash

input=$1
echo Input $input

# I want to start the following when input is test.Rnw
# /usr/bin/Rscript -e   'library(knitr); knit("test.Rnw")'

cmd_start="'library(knitr);knit(\""
cmd_end="\")'"

echo /usr/bin/Rscript -e  $cmd_start$input$cmd_end
/usr/bin/Rscript -e  $cmd_start$input$cmd_end

When running

./test.sh test.Rnw

output is

 Input test.Rnw
 /usr/bin/Rscript -e 'library(knitr);knit("test.Rnw")'
 [1] "library(knitr);knit(\"test.Rnw\")" 

So the command seems to be okay. But R isn't running knitr. Instead it handles the input as variable.

Running

 /usr/bin/Rscript -e 'library(knitr);knit("test.Rnw")'

does the right.

What am I missing?

Upvotes: 4

Views: 1432

Answers (1)

sgibb
sgibb

Reputation: 25736

Your problem is a double quoting: $cmd_start$input$cmd_end becomes 'library(knitr);knit(\"test.Rnw\")' but not 'library(knitr);knit("test.Rnw")'.

Try the following:

cmd_start='library(knitr);knit("'
cmd_end='")'

/usr/bin/Rscript -e  $cmd_start$input$cmd_end

Or:

/usr/bin/Rscript -e "library(knitr); knit(\"${input}\")"

Upvotes: 6

Related Questions