Dave
Dave

Reputation: 480

How to run a multi command Linux shell script from within R?

I am spinning up a linux virtual environment which is missing the needed drivers, so I am using the shell to install. I am doing this manually but would like to automate it from within R, where the rest of my code is.

I am able to open the shell in R by clicking on Tools>Shell...

I then have multiple lines of Bash script to run in order to install the "ODBC Driver 17 for SQL Server"

sudo su 
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
curl https://packages.microsoft.com/config/debian/8/prod.list > /etc/apt/sources.list.d/mssql-release.list

exit
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get install msodbcsql17

I would like to save these commands in some sort of readable file and run this from within R.

After some search I have seen posts that use System to run a single line but I have not been able to find information on if/how this can be extended to run multiple lines or how to pull these commands from some sort of saved file.

Context: I am new to linux and Bash/Shell commands Thank you!

Upvotes: 2

Views: 2339

Answers (2)

Ajjit Narayanan
Ajjit Narayanan

Reputation: 692

You can separate commands using ; and just store the entire script as a single character string. If you have special characters in your script (you don't currently) you are going to have to be very careful about correctly using escape characters.

For your bash script something like this should work

command="sudo su ; 
curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -; 
curl https://packages.microsoft.com/config/debian/8/prod.list > /etc/apt/sources.list.d/mssql-release.list; 
exit;
sudo apt-get update;
sudo ACCEPT_EULA=Y apt-get install msodbcsql17;"

system(command)

Another workaround is to save your script as a .sh bash script and just call the script filename within command(). Note that to make the bash script executable from the command line, you have to add the she-bang line (#!/bin/bash) at the very top.

Upvotes: 1

Ralf Stubner
Ralf Stubner

Reputation: 26823

Actually multi-line commands work just fine:

command <- "cd
pwd
ls"
system(command)

The problem with the commands provided by MS is the (unnecessary) use of su. You can rewrite the commands to use elevated privileges only where necessary:

command="curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
curl https://packages.microsoft.com/config/debian/8/prod.list | sudo tee /etc/apt/sources.list.d/mssql-release.list
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get install msodbcsql17"
system(command)

see for example here for sudo tee.

Upvotes: 1

Related Questions