Skip to content

Instantly share code, notes, and snippets.

@xavidp
Forked from padamson/installAllRPackages.bash
Created June 9, 2016 10:24
Show Gist options
  • Save xavidp/a6feb71ba8c0a2408c397a312560cd91 to your computer and use it in GitHub Desktop.
Save xavidp/a6feb71ba8c0a2408c397a312560cd91 to your computer and use it in GitHub Desktop.
Bash script to install all R packages required by an R program
#!/bin/bash
#Install any packages required by an R file that aren't already installed
if [ $# -ne 1 ]; then
echo $0: usage: installAllRPackages.bash file
exit 1
fi
file=$1
tempfile() {
tempprefix=$(basename "$0")
mktemp ~/tmp/${tempprefix}.XXXXXX
}
TMP1=$(tempfile)
TMP2=$(tempfile)
TMP3=$(tempfile)
trap 'rm -f $TMP1 $TMP2 $TMP3' EXIT
grep library $file >> $TMP1
grep require $file >> $TMP1
awk -F "[()]" '{ for (i=2; i<NF; i+=2) print $i }' $TMP1 >> $TMP2
while read p; do
truncate -s 0 $TMP3
sudo su - -c "R -q -e \"is.element('$p', installed.packages()[,1])\"" >> $TMP3
if grep -Fxq "[1] TRUE" $TMP3
then
echo "$p package already installed"
else
echo "installing $p package"
sudo su - -c "R -q -e \"install.packages('$p', repos='http://cran.rstudio.com/')\""
fi
done <$TMP2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment