You can use the commandArgs
function to get all the options that were passed by Rscript to the actual R interpreter and search them for --file=
. If your script was launched from the path or if it was launched with a full path, the script.name
below will start with a '/'
. Otherwise, it must be relative to the cwd
and you can concat the two paths to get the full path.
Edit: it sounds like you'd only need the script.name
above and to strip off the final component of the path. I've removed the unneeded cwd()
sample and cleaned up the main script and posted my other.R
. Just save off this script and the other.R
script into the same directory, chmod +x
them, and run the main script.
main.R:
#!/usr/bin/env Rscript
initial.options <- commandArgs(trailingOnly = FALSE)
file.arg.name <- "--file="
script.name <- sub(file.arg.name, "", initial.options[grep(file.arg.name, initial.options)])
script.basename <- dirname(script.name)
other.name <- paste(sep="/", script.basename, "other.R")
print(paste("Sourcing",other.name,"from",script.name))
source(other.name)
other.R:
print("hello")
output:
burner@firefighter:~$ main.R
[1] "Sourcing /home/burner/bin/other.R from /home/burner/bin/main.R"
[1] "hello"
burner@firefighter:~$ bin/main.R
[1] "Sourcing bin/other.R from bin/main.R"
[1] "hello"
burner@firefighter:~$ cd bin
burner@firefighter:~/bin$ main.R
[1] "Sourcing ./other.R from ./main.R"
[1] "hello"
This is what I believe dehmann is looking for.