通过 shell 脚本运行 R 脚本。意外标记“(”附近的语法错误

aaa*_*aaa 1 bash shell-script error-handling r syntax

我目前正在尝试通过 shell 脚本运行 R 脚本。

这里是 R 脚本:

test = rnorm(1:100, 1000)
write.csv(test, 'test.csv')
Run Code Online (Sandbox Code Playgroud)

这里是调用 R 的 bash 脚本:

#!/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
Run Code Online (Sandbox Code Playgroud)

我想我做的一切都正确,但输出返回以下错误:

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

为什么我收到此错误?

Ini*_*ian 5

问题是 shell 试图${HOME}/test.R用一个bash解释器运行你的解释器,它没有试图理解第 3 行的语法。R显式使用你想要test.R运行的解释器。

设置解释你Rscripttest.R

#!/usr/bin/env Rscript

module purge
module load R 
test = rnorm(1:100, 1000)
write.csv(test, 'test.csv')
Run Code Online (Sandbox Code Playgroud)

通过这种方式设置解释器,您现在可以从 shell 脚本运行它

Rscript ${HOME}/test.R
Run Code Online (Sandbox Code Playgroud)

请记住,登录到Rshell 并在其上运行命令,并在 shell 脚本中进行尝试是不一样的,Rshell与shell 不同bash。您需要使用不R直接从命令行登录的方式来运行命令,并在 shell 脚本中使用相同的方法。