透過 shell 腳本運行 R 腳本。意外標記“(”附近出現語法錯誤

透過 shell 腳本運行 R 腳本。意外標記“(”附近出現語法錯誤

我目前正在嘗試透過 shell 腳本運行 R 腳本。

這是 R 腳本:

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

這裡是呼叫 R 的 bash 腳本:

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

我認為我所做的一切都是正確的,但輸出返回以下錯誤:

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

為什麼我會收到此錯誤?

答案1

問題是 shell 正在嘗試使用${HOME}/test.R解釋器來運行您的程序bash,但它不會試圖理解第 3 行中的語法。Rtest.R

將您的解釋器Rscript設定test.R

#!/usr/bin/env Rscript

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

這樣,透過解釋器集,您現在可以從 shell 腳本運行它:

Rscript ${HOME}/test.R

請記住,登入Rshell 並在其上執行命令與在 shell 腳本中嘗試是不一樣的,Rshell 與 shell 不同bash。您需要使用無需直接從命令列登入的方式來執行命令R,並在 shell 腳本中使用相同的方法。

答案2

我在 Ubuntu 容器上運行腳本時遇到了同樣的問題,將 \r\n 替換為 \n 後它就可以工作了。使用文字編輯器開啟腳本並將所有 \r\n 替換為 \n

相關內容