1

I am currently trying to run an R script via a shell script.

Here the R script:

test = rnorm(1:100, 1000)
write.csv(test, 'test.csv')

And here the bash script which calls the R one:

#!/bin/bash -l
#SBATCH --partition=compute
#SBATCH --job-name=test
#SBATCH --mail-type=ALL
#SBATCH --mail-user=myemail@blabla.com
#SBATCH --time=00:10:00
#SBATCH --nodes=1
#SBATCH --tasks-per-node=12
#SBATCH --account=myaccount
module purge
module load R
${HOME}/test.R

I think I did everything correctly, but the output returns the following error:

/mydirectory/test.R: line 3: syntax error near unexpected token `('
/mydirectory/test.R: line 3: `test = rnorm(1:100, 1000)'

Why I did I get this error?

  • What is the output of ls -l ${HOME}/test.R? – Hauke Laging Dec 2 '17 at 13:20
  • here's the output: -rwxr--r-- 1 username Dec 2 11:37 /mydirectory/test.R – aaaaa Dec 2 '17 at 13:32
  • p.s. if I run test.R without the shell script it works fine. – aaaaa Dec 2 '17 at 13:37
  • 1
    @aaaaa: Can you show the complete command, on how you tested the R script to be working? – Inian Dec 2 '17 at 13:39
  • 2
    @aaaaa: Remember, logging into R and running the commands, and trying it out in the shell script is not the same, R shell is different from the bash shell. Figure out a way to run the commands without logging into R from the command line directly and use that same approach in the shell script – Inian Dec 2 '17 at 13:56
5

The problem is the shell is trying to the run your ${HOME}/test.R with a bash interpreter for which it is not trying to understand the syntax from the line number 3. Use the R interpreter explicitly from which you want the test.R to run from.

Set the interpreter for your Rscript in test.R as

#!/usr/bin/env Rscript

module purge
module load R 
test = rnorm(1:100, 1000)
write.csv(test, 'test.csv')

This way with the interpreter set, you can now run it from the shell script as

Rscript ${HOME}/test.R

Remember, logging into R shell and running the commands on it, and trying it out in the shell script are not the same, R shell is different from the bash shell. You need to use the way to run the commands without logging into R from the command line directly and use that same approach in the shell script.

  • I'm quite sure the module entries are actually bash functions: modules.sourceforge.net – liori Dec 2 '17 at 14:53
  • After adding the shebang, you can just call the script as ${HOME}/test.R, you don't need to prepend it with the interpreter anymore – Ferrybig Dec 2 '17 at 20:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.