4

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?

sgibb
  • 25,396
  • 3
  • 68
  • 74
JerryWho
  • 3,060
  • 6
  • 27
  • 49
  • As a work around I write the code library(knitr);knit("test.Rnw") in a temporary file and run this via Rscript tmpfile. But I think it's a little bit clumsy. – JerryWho Jul 06 '13 at 12:21
  • 1
    out of curiosity, why use `#!/bin/bash` and not `#!/usr/bin/Rscript` directly? You can then use `commandArgs()`, and R syntax in your script. – baptiste Jul 06 '13 at 13:20
  • @baptiste: My example is part of a bigger shell-script. So I can't use just Rscript. – JerryWho Jul 06 '13 at 16:28

1 Answers1

6

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}\")"
sgibb
  • 25,396
  • 3
  • 68
  • 74