Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
998 views
in Technique[技术] by (71.8m points)

bash - Specify which shell to use in R

I have to run a shell script inside R. I've considered using R's system function.

However, my script involves source activate and other commands that are not available in /bin/sh shell. Is there a way I can use /bin/bash instead?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Invoke /bin/bash, and pass the commands via -c option in one of the following ways:

system(paste("/bin/bash -c", shQuote("Bash commands")))
system2("/bin/bash", args = c("-c", shQuote("Bash commands")))

If you only want to run a Bash file, supply it with a shebang, e.g.:

#!/bin/bash -
builtin printf %q "/tmp/a b c"

and call it by passing script's path to the system function:

system("/path/to/script.sh")

It is implied that the current user/group has sufficient permissions to execute the script.

Rationale

Previously I suggested to set the SHELL environment variable. But it probably won't work, since the implementation of the system function in R calls the C function with the same name (see src/main/sysutils.c):

int R_system(const char *command)
{
    /*... */
    res = system(command);

And

The system() library function uses fork(2) to create a child process that executes the shell command specified in command using execl(3) as follows:

execl("/bin/sh", "sh", "-c", command, (char *) 0);

(see man 3 system)

Thus, you should invoke /bin/bash, and pass the script body via the -c option.

Testing

Let's list the top-level directories in /tmp using the Bash-specific mapfile:

test.R

script <- '
mapfile -t dir < <(find /tmp -mindepth 1 -maxdepth 1 -type d)
for d in "${dir[@]}"
do
  builtin printf "%s
" "$d"
done > /tmp/out'

system2("/bin/bash", args = c("-c", shQuote(script)))

test.sh

Rscript test.R && cat /tmp/out

Sample Output

/tmp/RtmpjJpuzr
/tmp/fish.ruslan
...

Original Answer

Try to set the SHELL environment variable:

Sys.setenv(SHELL = "/bin/bash")
system("command")

Then the commands passed to system or system2 functions should be invoked using the specified shell.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...