Home > Back-end >  Trying to call a shell script from an R script using system(). But the shell script is not found
Trying to call a shell script from an R script using system(). But the shell script is not found

Time:10-21

I am trying to call a shell script from an R script using R's system() function.

I am doing the following:

In my R script I call the system() function: system(exe, intern = TRUE,wait = TRUE), exe contains the necessary arguments for the shell script, starting with the file path from the R script directory to the shell script directory, to call the script.

This returns sh: 1: 'file-path-to-shell-script': not found

When I copy paste what is contained in exe, and run it directly in the command line, starting from the file location of the R script, it works perfectly.

Can anybody help me with this?

CodePudding user response:

I am assuming that you are using a relative path to your shell script. Execute getwd() within your script to make sure that your working directory corresponds to the directory that the script resides in. If your current working directory does not correpond to the location of your script you have a couple of options:

  1. use setwd() to set your working directory to the correct location so relative path to shell script will be correct.
  2. use the information provided by getwd() to correct your relative path
  3. use an absolute path to your shell script as the argument to system()

Example:

  • Your script is located in /home/bis/scripts and getwd() returns /home/bis/R/workspace.
  • The shell script you wish to execute is located in /home/bis
  • If you attempt to run system('../scripts/my-script.sh') within your script it will fail.
  • If you attempt to run system('../../scripts/my-script.sh') within your script it will succeed.

Hope this helps!

  • Related