使用R中的特定工作目录调用shell skript

时间:2016-07-28 11:38:58

标签: r shell

我有一个sh脚本,只能从特定目录运行,因为它会查找该目录中的文件而我不想更改sh文件。

假设文件位于./sub/script.sh且R工作目录为./

什么有效

wd = getwd()
setwd("./sub")
system2("./script.sh")
setwd(wd)

但我觉得这很不方便。如何在不改变R工作目标的情况下做到这一点?

2 个答案:

答案 0 :(得分:2)

这不是很好,但是工作

# A function that will call the script
test <- function(){

  # Current working directory
  cur <- getwd(); 

  # On exit, come back
  on.exit(setwd(cur)); 

  # Change directory
  setwd("~"); 

  # Run the command
  system("pwd"); 

  # Return
  NULL
}

然后只需调用函数test()

答案 1 :(得分:1)

由于system2使用shQuote,我们只能使用system(),正如@Dirk已经指出的那样,您可以使用

system("cd ./sub && sh script.sh")