简体   繁体   中英

Passing arguments from a call to a bash script to an Rscript

I have a bash script that does some things and then calls Rscript. Here a simple example to illustrate:

test.sh:

Rscript test.r

test.r:

args <- commandArgs()
print(args)

How can I use ./test.sh hello on the command line result in R printing hello?

You can have bash pass all the arguments to the R script using something like this for a bash script:

#!/bin/bash

Rscript /path/to/R/script --args "$*"

exit 0

You can then choose how many of the arguments from $* need to be discarded inside of R.

I noticed the way to deal with this is:

test.sh:

Rscript test.r $1

test.r:

args <- commandArgs(TRUE)
print(args)

The $1 represents the first argument passed to the bash script.

When calling commandArgs() instead of commandArgs(TRUE) , it does not pass from bash, but instead it will print other arguments called internally.

Regarding asb's answer:

having "--args" in the line of bash script doesn't work, the "--args" was taken as the literal of real argument that I want to pass into my R script. Taking it out works, ie "Rscript /path/to/my/rfile.R arg1 arg2"

bash version: GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu) Rscript version: R scripting front-end version 3.0.1 (2013-05-16)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM