RMarkdown: How to pass arguments to bash chunk defined as variables in R?

Viewed 260

Cross-posted

I want to use variables defined in R environment as an argument in the bash chunk. Is there any way to do that?

For instance, in the examples below I want to use R to define the path to the script and pass it as an argument to bash:

```{r}
path_to_script <- glue("{here::here()}/bash_scripts/script.sh")
\```

```{bash}
bash  **path_to_script**
\```
2 Answers

I don't think the knitr bash engine does any substitutions, but you should be able to write to an environment variable, and use that from bash.

For example,

---
title: "Untitled"
date: "09/12/2021"
output: html_document
---


```{r}
msg <- shQuote("This is a message from R.")
Sys.setenv(R_MESSAGE = msg)
```

```{bash}
echo $R_MESSAGE
```

which produces this output:

enter image description here

I added the shQuote() call after reading @Fravadona's comment: it is definitely a really good idea, since the path you are constructing may contain spaces or other special characters.

Thank you @user2554330 for your suggestion. Indeed it seems to be working in the way I explained in my question. However, a little simpler solution was suggested here. Namely, don't use a bash chunk and instead create a string with full command and pass it to the system() function in R. In this case, I can do everything within the same environment.

```{r}
path_to_script <- glue("{here::here()}/bash_scripts/script.sh")
arg1 <- "something"
full_command <- glue("bash {path_to_script} {arg1}")
system(full_command)
```
Related