4

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?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

0

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, i.e. "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)

1 Comment

I found this worked in combination with the TRUE argument passed to commandArgs().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.