I give a walkthrough of a bash script that installs all of the R packages required by an R program (e.g., Shiny app, R file, R markdown file). This is useful for speeding up the workflow of adding a new Shiny app to a server.
Why do we need a script?
As explained in Dean Attali’s excellent post on how to setup an RStudio
and Shiny server,
you can install an R package (for example ‘mypackage’) for
everyone on a server at the command line with:1
Repeating this long command once or twice is fine, but if you have an app that
requires several R packages such as:
then you want to automate the task of installing missing R packages.
The bash script
For the impatient among you, here is the entire script:
The one argument passed to the script is the location of the R file that
require(mypackage) commands (each on a separate line). The script will
determine whether or not each required
package is installed, and if it is not, the package will be
installed from CRAN.
The first few lines simply check to make sure that a single argument
is provided. If not, a usage reminder is echoed and the script exits.
Otherwise, the argument is saved so that it is available in the
The next set of lines creates three temporary files in the ‘~/tmp’ directory
(it must exist!) and sets a trap to delete them on exit.
The next two lines employ
grep to search the R file for
require commands, placing any lines containing the commands in the temporary
awk is used to extract the name of each package by looking
inside the parenthesis on each line of the
The end result is a
$TMP2 file that contains the name of an R
package on each line.
The real meat of the script is in the final
while loop. In each
iteration of the loop, a package name is extracted from
stored in the variable
$p. We will reuse the
$TMP3 file, so
we empty it with the
truncate command at the start of each loop.
Also inside the loop, the command
calls R to check to see if the package name is an element of the array
returned from the
installed.packages() command. The result is stored in
$TMP3. If the R command returns
 TRUE, then on to the
next package. Otherwise, the package is installed.
Note that I added the
-qargument to suppress printing of the startup message. ↩