1

I would like to use the directory of my bat file to run my R script. My R script is in the same directory as my bat file, I tried:

"C:\Program Files\R\R-3.1.2\bin\x64\RScript.exe" "%CD%\script_to_run.R"

but the cmd immediately closes. This works if I specify the entire path of my script instead of using %CD%.

Can I have some help, please?

Pravitha V
  • 3,308
  • 4
  • 33
  • 51
A.Cle
  • 15
  • 6
  • Are you guessing that %CD% contains your current working directory? Try inserting echo %CD% before the command where you use it. – SPlatten Aug 24 '17 at 10:46
  • I thought %CD% contains the directory of my batch file. Is the current working directory the directory of the batch file when you execute it? – A.Cle Aug 24 '17 at 10:50
  • Try the echo and see. – SPlatten Aug 24 '17 at 10:51
  • echo %CD% doesn't work – A.Cle Aug 24 '17 at 10:54
  • when you say it doesn't work, is there an error or no result, if there isn't anything displayed and no error then it means that %CD% is empty, which would explain your problem, I don't think %CD% is one of those automatic variables that is set-up for you. – SPlatten Aug 24 '17 at 10:55
  • I've just created a simple batch file on Windows 7 system containing just echo %CD%, it does work on Windows 7, which OS are you using and version? – SPlatten Aug 24 '17 at 10:57
  • I'm using Windows 10. I tried "%CD%\script_to_run.r" and this works but I would like to run this script without opening my R program (that's why I specify its directory before) and this doesn't work – A.Cle Aug 24 '17 at 11:02
  • Why don't you add the path of the file you want to run to the PATH environment variable? The system uses the PATH environment variable to determine which folders to search in the order they are defined. – SPlatten Aug 24 '17 at 11:03
  • Maybe [this](https://stackoverflow.com/a/25440709/2861476) could help – MC ND Aug 24 '17 at 11:08
  • Sorry I'm a beginner, could you give an example of how to re-use the cd please? – A.Cle Aug 24 '17 at 11:26

2 Answers2

0

To start, or run a program in a batch script, you have to right start at the beginning. It would look like this,

start yourfilepath

I hope this helps, if not, tell me and I will try to help.

Oqhax
  • 419
  • 1
  • 4
  • 16
  • This is not exactly what I am looking for. I first specify the directory of my R program I want to run my R script with and then the path of my R script which is actually in the same folder as my bat file. I need to use the directory of my bat file for my R script to be able to execute it even if I change their directory. – A.Cle Aug 24 '17 at 10:53
0

The simplest fix is to use:

"C:\Program Files\R\R-3.1.2\bin\x64\RScript.exe" "%~dp0script_to_run.R"

Where %0 references the running batch script and %~dp0 references the drive and path of the running batch script, (ending with a trailing back slash).

Compo
  • 36,585
  • 5
  • 27
  • 39