Refactor: improved arg handling, added usage, colors and better messaging.

https://betterdev.blog/minimal-safe-bash-script-template/
master
Taha Ahmed 3 years ago
parent 0534288dcc
commit cab448cfd5

@ -1,39 +1,138 @@
#!/usr/bin/env bash #!/usr/bin/env bash
## Process *.Rnw files
## Written May 14, 2010 ## Written May 14, 2010
## Taha Ahmed ## Taha Ahmed
#################################################### # This is the first bash script where I implemented the ideas outlined by
# For now, MAKE SURE that the argument consists of # https://betterdev.blog/minimal-safe-bash-script-template/
# a complete filename, with extension, and
# in the directory of the Rnw file # I don't understand the point of traps, so I skipped "-E"
#################################################### # https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
set -euo pipefail
usage() {
cat <<EOF
Usage: $(basename "${BASH_SOURCE[0]}") [arg1]
Compiles Rnw documents with knitr and latexmk. This is a highly customised script.
Takes zero or one arguments. The argument must be a filename with the extension "Rnw".
If an argument is supplied, the document in question is compiled.
If no arguments are supplied, a menu is displayed offering a choice of auxiliary tasks.
This script treats certain filenames in a special manner:
+ "thesis" --> triggers a chain of special commands, see source code.
In addition, the internal execution of this script is modified by the existence of
certain files in the working directory:
+ .knitme --> use knitr::knit() instead of pgfSweave().
+ .latexmkrc --> apply RC file to latexmk command.
+ vc --> run vc script (integrates git with LaTeX, deprecated by gitinfo2, kept for backwards support).
EOF
exit
}
# keep track of runtime of entire script # keep track of runtime of entire script
starttime=$(date +%s) starttime=$(date +%s)
# in future, consider integrating this color setup with ~/.local/bin/echo-colours.sh
setup_colors() {
if [[ -t 2 ]] && [[ -z "${NO_COLOR-}" ]] && [[ "${TERM-}" != "dumb" ]]; then
NOFORMAT='\033[0m'
# text color
Black='\033[0;30m' Red='\033[0;31m' Green='\033[0;32m' Yellow='\033[0;33m' Blue='\033[0;34m' Purple='\033[0;35m' Cyan='\033[0;36m' White='\033[0;37m'
# bold text and color
BBlack='\033[1;30m' BRed='\033[1;31m' BGreen='\033[1;32m' BYellow='\033[1;33m' BBlue='\033[1;34m' BPurple='\033[1;35m' BCyan='\033[1;36m' BWhite='\033[1;37m'
# underline and color
UBlack='\033[4;30m' URed='\033[4;31m' UGreen='\033[4;32m' UYellow='\033[4;33m' UBlue='\033[4;34m' UPurple='\033[4;35m' UCyan='\033[4;36m' UWhite='\033[4;37m'
# text on background color
On_Black='\033[40m' On_Red='\033[41m' On_Green='\033[42m' On_Yellow='\033[43m' On_Blue='\033[44m' On_Purple='\033[45m' On_Cyan='\033[46m' On_White='\033[47m'
# high intensity color
IBlack='\033[0;90m' IRed='\033[0;91m' IGreen='\033[0;92m' IYellow='\033[0;93m' IBlue='\033[0;94m' IPurple='\033[0;95m' ICyan='\033[0;96m' IWhite='\033[0;97m'
# bold high intensity color
BIBlack='\033[1;90m' BIRed='\033[1;91m' BIGreen='\033[1;92m' BIYellow='\033[1;93m' BIBlue='\033[1;94m' BIPurple='\033[1;95m' BICyan='\033[1;96m' BIWhite='\033[1;97m'
# text on high intensity background color
On_IBlack='\033[0;100m' On_IRed='\033[0;101m' On_IGreen='\033[0;102m' On_IYellow='\033[0;103m' On_IBlue='\033[0;104m' On_IPurple='\033[0;105m' On_ICyan='\033[0;106m' On_IWhite='\033[0;107m'
else
NOFORMAT=''
Black='' Red='' Green='' Yellow='' Blue='' Purple='' Cyan='' White=''
BBlack='' BRed='' BGreen='' BYellow='' BBlue='' BPurple='' BCyan='' BWhite=''
UBlack='' URed='' UGreen='' UYellow='' UBlue='' UPurple='' UCyan='' UWhite=''
On_Black='' On_Red='' On_Green='' On_Yellow='' On_Blue='' On_Purple='' On_Cyan='' On_White=''
IBlack='' IRed='' IGreen='' IYellow='' IBlue='' IPurple='' ICyan='' IWhite=''
BIBlack='' BIRed='' BIGreen='' BIYellow='' BIBlue='' BIPurple='' BICyan='' BIWhite=''
On_IBlack='' On_IRed='' On_IGreen='' On_IYellow='' On_IBlue='' On_IPurple='' On_ICyan='' On_IWhite=''
fi
}
msg() {
echo >&2 -e "${1-}"
}
# examples:
# die "Some message (exiting with status 1)"
# die "Some message (exiting with status -->)" 0
die() {
local msg=$1
local code=${2-1} # default exit status 1
msg "$msg"
simpledelay.sh 2 # short delay to aid reading last message in case terminal closes on exit
exit "$code"
}
parse_params() {
while :; do
case "${1-}" in
-h | --help) usage ;;
-v | --verbose) set -x ;;
--no-color) NO_COLOR=1 ;;
-?*) die "Unknown option: $1" ;;
*) break ;;
esac
shift
done
args=("$@")
# Check number of arguments
# this script can be run with one argument is process mode or with zero arguments in post-processing mode
[[ ${#args[@]} -gt 1 ]] && die "More than one argument not supported"
# we use maintrack variable to keep track of whether auxiliary menu should be entered
[[ ${#args[@]} -eq 1 ]] && maintrack=true
return 0
}
maintrack=false # I'm not really happy with this variable *name*
parse_params "$@"
setup_colors
clear clear
echo "-----------------------------------------------------------------------" msg "-----------------------------------------------------------------------"
echo "cheRTeX -- a script for processing R--Sweave/knitr--LaTeX/TikZ projects" msg "cheRTeX -- a script for processing R--Sweave/knitr--LaTeX/TikZ projects"
echo "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" msg "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"
echo "MMXVI -- taha@chepec.se -- CHEPEC doctoral degree project" msg "MMXX -- taha@chepec.se -- CHEPEC doctoral degree project"
echo "-----------------------------------------------------------------------" msg "-----------------------------------------------------------------------"
## If the file .latexmkrc exists in the current directory,
## set the flag ltxmkrc=TRUE ## If the file .latexmkrc exists in the current directory, set ltxmkrc=TRUE
ltxmkrc=false ltxmkrc=false
echo "--- Looking for .latexmkrc" msg "--- Looking for .latexmkrc"
if [ -e .latexmkrc ]; then if [ -e .latexmkrc ]; then
ltxmkrc=true ltxmkrc=true
echo "+++ LaTeXMK RC file invoked" msg "+++ LaTeXMK RC file invoked"
else else
echo "--- This job did not request LaTeXMK RC file" msg "--- This job did not request LaTeXMK RC file"
fi fi
# define some constants # define some constants
path_wd=${PWD} path_wd=${PWD}
dir_wd=$(basename $path_wd) dir_wd=$(basename $path_wd)
path_thesis="/media/bay/taha/chepec/thesis" path_thesis="/media/bay/taha/chepec/thesis"
temp_folder="/media/bay/taha/chepec/tmp"
# define some file types # define some file types
Rfiletype="R" Rfiletype="R"
@ -80,59 +179,37 @@ aux_xdy="*.xdy" # glossaries (xindy)
auxfiles="${aux_acn} ${aux_acr} ${aux_alg} ${aux_aux} ${aux_bbl} ${aux_blg} ${aux_dep} ${aux_dpth} ${aux_fdb} ${aux_fig} ${aux_fls} ${aux_glg} ${aux_glo} ${aux_gls} ${aux_ist} ${aux_lob} ${aux_lof} ${aux_log} ${aux_lor} ${aux_los} ${aux_lot} ${aux_maf} ${aux_out} ${aux_lox} ${aux_make} ${aux_map} ${aux_mtc} ${aux_run} ${aux_slg} ${aux_slo} ${aux_sls} ${aux_tikz} ${aux_tdo} ${aux_toc} ${aux_xdy}" auxfiles="${aux_acn} ${aux_acr} ${aux_alg} ${aux_aux} ${aux_bbl} ${aux_blg} ${aux_dep} ${aux_dpth} ${aux_fdb} ${aux_fig} ${aux_fls} ${aux_glg} ${aux_glo} ${aux_gls} ${aux_ist} ${aux_lob} ${aux_lof} ${aux_log} ${aux_lor} ${aux_los} ${aux_lot} ${aux_maf} ${aux_out} ${aux_lox} ${aux_make} ${aux_map} ${aux_mtc} ${aux_run} ${aux_slg} ${aux_slo} ${aux_sls} ${aux_tikz} ${aux_tdo} ${aux_toc} ${aux_xdy}"
# depending on number of args and their content, do different things... if $maintrack; then
if [ $# -eq 1 ]; then
# Check if the argument contains a filetype # Check if the argument contains a filetype
# (assumes a complete filename was passed) # (assumes a complete filename was passed)
jobfilename=$1 jobfilename=${args[0]}
jobfiletype=${jobfilename#*.} # File extension jobfiletype=${jobfilename#*.} # File extension
jobname=${jobfilename%.*} # Filename without extension part jobname=${jobfilename%.*} # Filename without extension part
echo "<cheRTeX> Detected filename: " $jobname msg "<cheRTeX> Detected filename: $jobname"
echo "<cheRTeX> Detected extension:" $jobfiletype msg "<cheRTeX> Detected extension: $jobfiletype"
# Verify that the file extension is "[Rr][Nn][Ww]" # Verify that the file extension is "[Rr][Nn][Ww]"
if [[ $jobfiletype == "Rnw" || $jobfiletype == "rnw" || $jobfiletype == "RNW" ]]; then if [[ $jobfiletype == "Rnw" || $jobfiletype == "rnw" || $jobfiletype == "RNW" ]]; then
# File extension is indeed "[Rr][Nn][Ww]" # File extension is indeed "[Rr][Nn][Ww]"
echo "<cheRTeX> Detected *.Rnw extension" msg "<cheRTeX> Detected *.Rnw extension"
jobfiletype="Rnw" jobfiletype="Rnw"
else else
# File extension is NOT "[Rr][Nn][Ww]" # File extension is NOT "[Rr][Nn][Ww]"
echo "<cheRTeX> This script only handles *.Rnw files" die "This script only supports *.Rnw files"
echo "<cheRTeX> Terminating..."
exit 1
fi fi
# Introducing a short delay to enable on-screen reading of previous echo # Introducing a short delay to enable on-screen reading of previous echo
simpledelay.sh 2 simpledelay.sh 2
# no need to echo it
# echo "Delay completed"
#### Special treatment for sample-matrix.Rnw
# If $jobname is sample-matrix, restart Shiny and term this script
if [[ $jobname == "sample-matrix" ]]; then
echo "<sample-matrix> -------------------------------"
echo "<sample-matrix> Restarting Shiny"
echo "<sample-matrix> -------------------------------"
# kill Shiny
pkill -f "shiny::runApp"
# start Shiny
bash -c "/media/bay/taha/chepec/chetex/common/bash/shiny-matrix.sh" &
# terminate this script
echo "<cheRTeX> Terminating..."
simpledelay.sh 2
exit 0
fi
#### Special treatment for thesis #### Special treatment for thesis
if [[ $path_wd == "$path_thesis" && $jobname == "$dir_wd" ]]; then if [[ $path_wd == "$path_thesis" && $jobname == "$dir_wd" ]]; then
# Fetch external assets by reading any assets.external files in assets/ tree # Fetch external assets by reading any assets.external files in assets/ tree
# NOTE: be careful NOT to leave empty lines in your assets.external files # NOTE: be careful NOT to leave empty lines in your assets.external files
echo "<thesis> -------------------------------" msg "<thesis> -------------------------------"
echo "<thesis> Getting external assets" msg "<thesis> Getting external assets"
echo "<thesis> -------------------------------" msg "<thesis> -------------------------------"
# find all files named "assets.external" in the assets/ tree # find all files named "assets.external" in the assets/ tree
assetsexternalfiles=$(find "$path_wd/assets/" -type f -name "assets.external") assetsexternalfiles=$(find "$path_wd/assets/" -type f -name "assets.external")
for externalfilepath in $assetsexternalfiles; do for externalfilepath in $assetsexternalfiles; do
@ -152,13 +229,10 @@ if [ $# -eq 1 ]; then
read -ra asset_array <<< "$asset" read -ra asset_array <<< "$asset"
# sanity check for array length # sanity check for array length
if [ ${#asset_array[@]} -gt 2 ]; then if [ ${#asset_array[@]} -gt 2 ]; then
echo "<thesis> Cannot handle more than one $IFS character per line" die "<thesis> Cannot handle more than one $IFS character per line"
echo "<cheRTeX> Terminating..."
simpledelay.sh 2
exit 1
fi fi
if [ ${#asset_array[@]} -gt 1 ]; then if [ ${#asset_array[@]} -gt 1 ]; then
# echo "Placing this asset into subdirectory ${asset_array[1]}" # msg "Placing this asset into subdirectory ${asset_array[1]}"
# redefine assetpathtarget to include the local subdir # redefine assetpathtarget to include the local subdir
assetpathtarget="$assetpathtarget/${asset_array[1]}" assetpathtarget="$assetpathtarget/${asset_array[1]}"
# also redefine $asset so we keep only the asset path # also redefine $asset so we keep only the asset path
@ -166,22 +240,22 @@ if [ $# -eq 1 ]; then
# create the local subdir inside assets/<current/ # create the local subdir inside assets/<current/
mkdir -p "$assetpathtarget" # -p suppresses error if dir already exists mkdir -p "$assetpathtarget" # -p suppresses error if dir already exists
fi fi
echo "<thesis> Copying $asset to $assetpathtarget" msg "<thesis> Copying $asset to $assetpathtarget"
# cp but don't overwrite existing files # cp but don't overwrite existing files
cp --preserve=timestamps --no-clobber --recursive $asset $assetpathtarget cp --preserve=timestamps --no-clobber --recursive $asset $assetpathtarget
# except we want to overwrite the BibTeX library files (inside the assets/references/ directory), we'll do that by checking the target dirname and only running the destructive cp operation if its "references" # except we want to overwrite the BibTeX library files (inside the assets/references/ directory), we'll do that by checking the target dirname and only running the destructive cp operation if its "references"
assetdirnametarget=$(basename "$assetpathtarget") assetdirnametarget=$(basename "$assetpathtarget")
if [[ $assetdirnametarget == "references" ]]; then if [[ $assetdirnametarget == "references" ]]; then
echo "<thesis> Overwriting BibTeX libraries in assets/references/" msg "<thesis> Overwriting BibTeX libraries in assets/references/"
cp --preserve=timestamps $asset $assetpathtarget cp --preserve=timestamps $asset $assetpathtarget
fi fi
done < "$externalfilepath" done < "$externalfilepath"
done done
# Create low-res photos on-the-fly from existing photos/ # Create low-res photos on-the-fly from existing photos/
echo "<thesis> -------------------------------" msg "<thesis> -------------------------------"
echo "<thesis> Create low-res photos tree" msg "<thesis> Create low-res photos tree"
echo "<thesis> -------------------------------" msg "<thesis> -------------------------------"
# copy existing photos to assets/photos/.lowres/ path # copy existing photos to assets/photos/.lowres/ path
# to save time, rsync only if highres photo has more recent timestamp (otherwise, keep lowres photo without overwriting) # to save time, rsync only if highres photo has more recent timestamp (otherwise, keep lowres photo without overwriting)
# Note: rsync usually looks at file timestamp and size, and if either has changed, copies the file (simplified explanation) # Note: rsync usually looks at file timestamp and size, and if either has changed, copies the file (simplified explanation)
@ -205,21 +279,19 @@ if [ $# -eq 1 ]; then
# revert the effects of cd above. Redirect to null suppresses the output. # revert the effects of cd above. Redirect to null suppresses the output.
cd - >/dev/null cd - >/dev/null
# Convert all non-JPG images (except for PDF, SVG, and other non-images) to JPG # Convert all non-JPG images (except for PDF, SVG, and other non-images) to JPG
echo "<thesis> Convert all non-JPG images to JPG" msg "<thesis> Convert all non-JPG images to JPG"
find "$path_thesis/assets/photos/.lowres/" -type f ! -name "*.pdf" ! -name "*.svg" ! -name "*.external" ! -name "lastrun" ! -name "*.jpg" -print -exec mogrify -format jpg "{}" \; find "$path_thesis/assets/photos/.lowres/" -type f ! -name "*.pdf" ! -name "*.svg" ! -name "*.external" ! -name "lastrun" ! -name "*.jpg" -print -exec mogrify -format jpg "{}" \;
# Remove the now redundant non-JPG files in .lowres/ # Remove the now redundant non-JPG files in .lowres/
echo "<thesis> Delete the redundant non-JPG files in .lowres/ tree" msg "<thesis> Delete the redundant non-JPG files in .lowres/ tree"
find "$path_thesis/assets/photos/.lowres/" -type f ! -name "*.pdf" ! -name "*.svg" ! -name "*.external" ! -name "lastrun" ! -name "*.jpg" -print -exec rm "{}" \; find "$path_thesis/assets/photos/.lowres/" -type f ! -name "*.pdf" ! -name "*.svg" ! -name "*.external" ! -name "lastrun" ! -name "*.jpg" -print -exec rm "{}" \;
# Shrink image filesize in-place to roughly 300kb in size # Shrink image filesize in-place to roughly 300kb in size
echo "<thesis> Shrink images in .lowres/ tree to <=300K" msg "<thesis> Shrink images in .lowres/ tree to <=300K"
# https://stackoverflow.com/questions/6917219/imagemagick-scale-jpeg-image-with-a-maximum-file-size # https://stackoverflow.com/questions/6917219/imagemagick-scale-jpeg-image-with-a-maximum-file-size
find "$path_thesis/assets/photos/.lowres/" -size +500k -type f -name "*.jpg" -print -exec convert "{}" -define jpeg:extent=300kb "{}" \; find "$path_thesis/assets/photos/.lowres/" -size +500k -type f -name "*.jpg" -print -exec convert "{}" -define jpeg:extent=300kb "{}" \;
# update the modification and access time on the photosastrun file # update the modification and access time on the photosastrun file
touch "$photoslastrun" touch "$photoslastrun"
fi fi
# short delay to enable on-screen reading of previous echo
simpledelay.sh 2
## Handle knitr or pgfSweave jobs (each requires separate treatment) ## Handle knitr or pgfSweave jobs (each requires separate treatment)
@ -228,181 +300,138 @@ if [ $# -eq 1 ]; then
## IN ALL KNITR DIRECTORIES, CREATE A FILE NAMED: .knitme ## IN ALL KNITR DIRECTORIES, CREATE A FILE NAMED: .knitme
# If the file .knitme exists in the current directory, # If the file .knitme exists in the current directory,
# run knitr commands, otherwise run pgfsweave commands # run knitr commands, otherwise run pgfsweave commands
echo "--- Looking for .knitme" msg "--- Looking for .knitme"
if [ -e .knitme ]; then if [ -e .knitme ]; then
# Run knitr commands for this job # Run knitr commands for this job
echo "<cheRTeX> -----------------------" msg "<cheRTeX> -----------------------"
echo "<cheRTeX> This is a job for knitr" msg "<cheRTeX> This is a job for knitr"
echo "<cheRTeX> -----------------------" msg "<cheRTeX> -----------------------"
# Knit # Knit
echo "<cheRTeX> Knitting..." msg "<cheRTeX> Knitting..."
Rscript -e "library(knitr); library(methods); knit('$jobname.$jobfiletype')" Rscript -e "library(knitr); library(methods); knit('$jobname.$jobfiletype')"
# Introduce delay to give time to read Rscript exit status # Introduce delay to give time to read Rscript exit status
echo "<cheRTeX> -----------------------" msg "<cheRTeX> -----------------------"
echo "<cheRTeX> Rscript knitr completed" msg "<cheRTeX> Rscript knitr completed"
echo "<cheRTeX> -----------------------" msg "<cheRTeX> -----------------------"
simpledelay.sh 2 simpledelay.sh 2
else else
# Run pgfSweave commands # Run pgfSweave commands
echo "<cheRTeX> ---------------------------" msg "<cheRTeX> ---------------------------"
echo "<cheRTeX> This is a job for pgfSweave" msg "<cheRTeX> This is a job for pgfSweave"
echo "<cheRTeX> ---------------------------" msg "<cheRTeX> ---------------------------"
# Tangle # Tangle
echo "<cheRTeX> Tangling..." msg "<cheRTeX> Tangling..."
R CMD Stangle $jobname.$jobfiletype R CMD Stangle $jobname.$jobfiletype
# Weave # Weave
echo "<cheRTeX> Weaving..." msg "<cheRTeX> Weaving..."
R CMD pgfsweave --graphics-only $jobname.$jobfiletype R CMD pgfsweave --graphics-only $jobname.$jobfiletype
# Introduce delay to give time to read R CMD exit status # Introduce delay to give time to read R CMD exit status
echo "<cheRTeX> -------------------------" msg "<cheRTeX> -------------------------"
echo "<cheRTeX> R CMD pgfsweave completed" msg "<cheRTeX> R CMD pgfsweave completed"
echo "<cheRTeX> -------------------------" msg "<cheRTeX> -------------------------"
simpledelay.sh 2 simpledelay.sh 2
fi fi
# Run vc script if vc exists in working directory # Run vc script if vc exists in working directory
echo "<cheRTeX> Running vc script" msg "<cheRTeX> Running vc script..."
if [ -f vc ]; then if [ -f vc ]; then
./vc ./vc
fi fi
# Run pdflatex, bibtex, and company # Run pdflatex, bibtex, and company
if $ltxmkrc; then if $ltxmkrc; then
echo "<cheRTeX> Calling LaTeXMK with RC file" msg "${On_Cyan}<cheRTeX> Calling LaTeXMK with RC file${NOFORMAT}"
simpledelay.sh 2 simpledelay.sh 2
latexmk -r .latexmkrc -pdf -bibtex $jobname latexmk -r .latexmkrc -pdf -bibtex $jobname
else else
echo "<cheRTeX> Calling LaTeXMK" msg "${On_Cyan}<cheRTeX> Calling LaTeXMK${NOFORMAT}"
simpledelay.sh 2 simpledelay.sh 2
latexmk -pdf -bibtex $jobname latexmk -pdf -bibtex $jobname
fi fi
else else
# Either no arguments, or more than one argument # Zero arguments (the case of more than one argument is handled in parse_params above)
if [ $# -eq 0 ]; then # In this case, present a menu of choices
# Zero arguments. Present a menu of choices msg "This is cheRTeX POST-PROCESSING" # only one choice for now
echo "This is cheRTeX POST-PROCESSING" # only one choice for now msg "<1> 'pdf-all' -- Process all .tikz files to pdf graphics"
echo "<1> 'pdf-all' -- Process all .tikz files to pdf graphics" msg "<2> 'clean-up' -- Remove all auxiliary files"
echo "<2> 'clean-up' -- Remove all auxiliary files" msg "<3> 'wipe-dir' -- Remove all non-essential files and subdirectories"
echo "<3> 'wipe-dir' -- Remove all non-essential files and subdirectories" msg "Any other input exits the program"
echo "Any other input exits the program" read usrchoice
read usrchoice
if [[ $usrchoice == "pdf-all" || $usrchoice == "1" ]]; then
## Determine number of .Rnw files in current directory msg "<1> 'pdf-all' chosen"
#Rnwfileno=$(ls -1 $Rnwfiles | wc -l) # This for loop ONLY USED to determine number of *.tikz files in directory
#echo "No of .Rnw files: $Rnwfileno" for tikzfiles in "$tikzfiles"; do tikzfilenumber=${#tikzfiles}; done
# msg "cheRTeX detected $tikzfilenumber TikZ files for processing"
## Check if number of .Rnw files larger than one msg "Starting TikZ file processing..."
#if [ $Rnwfileno -gt 1 ]; then simpledelay.sh 2
# # If larger than one, ask for user input for tikzfilename in $tikzfiles; do
# # Indicates more than one Rnw file in current directory. # Call tikz2pdf
# # This introduces a naming ambiguity. msg "<Executing> tikz2pdf $tikzfilename"
# # Resolve by asking user for current jobname tikz2pdf --once $tikzfilename
# echo "Found $Rnwfileno .Rnw files in current directory" done
# echo "Please specify the jobname" msg "Completed TikZ file processing"
# read jobname fi
# if [ -z "$jobname" ]; then if [[ $usrchoice == "clean-up" || $usrchoice == "2" ]]; then
# # string is null msg "<2> 'clean-up' chosen"
# echo "Specified jobname cannot be parsed. Terminating..." rm $auxfiles
# exit 1 # Still, a rather crude way of cleaning up...
# fi fi
#else if [[ $usrchoice == "wipe-dir" || $usrchoice == "3" ]]; then
## There is exactly one *.Rnw file is current directory msg "<3> 'wipe-dir' chosen"
## Fetch the jobname from the .Rnw filename by stripping off the file extension ## Remove all but non-essential files
# Rnwfilename=$(ls -1 $Rnwfiles) # get a timestamp
# jobname=${Rnwfilename%.*} timestamp=$(date +%s)
#fi # create a unique tmp-dir name
# tmpdirname="${timestamp}-${dir_wd}"
#echo "Jobname set to: $jobname" # make a directory in chepec/tmp with the name of the current dir
mkdir $temp_folder/$tmpdirname
if [[ $usrchoice == "pdf-all" || $usrchoice == "1" ]]; then # Copy the contents of the current directory to the tmp/$currdirname directory
echo "<1> 'pdf-all' chosen" cp * -R $temp_folder/$tmpdirname
# This for loop ONLY USED to determine number of *.tikz files in directory # Empty the current directory of all contents
for tikzfiles in "$tikzfiles"; do tikzfilenumber=${#tikzfiles}; done rm * -R # note: hidden files and subdir unaffected
echo "cheRTeX detected $tikzfilenumber TikZ files for processing" # Return the stuff we want to keep after wipe-dir
echo "Starting TikZ file processing..." # (we are of course assuming that the following 4 file(type)s always exist)
simpledelay.sh 2 # (if in fact they do not exist, use conditional statements instead (see below)
cp $temp_folder/$tmpdirname/*.Rnw .
for tikzfilename in $tikzfiles; do cp $temp_folder/$tmpdirname/vc .
# Call tikz2pdf cp $temp_folder/$tmpdirname/vc.tex .
echo "<Executing> tikz2pdf $tikzfilename" cp $temp_folder/$tmpdirname/vc-git.awk .
tikz2pdf --once $tikzfilename ## Return stuff that may not always exist (check first...)
done ## The use of conditionals is mainly to avoid annoying "file does not exist" messages...
echo "Completed TikZ file processing" # Return *.Rproj file (removal is unnecessary and makes RStudio less useful)
fi Rprojfiles=`ls -1 $temp_folder/$tmpdirname/*.Rproj 2>/dev/null | wc -l`
if [ $Rprojfiles != 0 ]; then
if [[ $usrchoice == "clean-up" || $usrchoice == "2" ]]; then cp $temp_folder/$tmpdirname/*.Rproj .
echo "<2> 'clean-up' chosen"
rm $auxfiles
# Still, a rather crude way of cleaning up...
fi fi
# Return *.rda files (considering peak-data files, which "cost" a lot to create)
if [[ $usrchoice == "wipe-dir" || $usrchoice == "3" ]]; then rdafiles=`ls -1 $temp_folder/$tmpdirname/*.rda 2>/dev/null | wc -l`
echo "<3> 'wipe-dir' chosen" if [ $rdafiles != 0 ]; then
## Remove all but non-essential files cp $temp_folder/$tmpdirname/*.rda .
# get the name of the current directory
currdirname=${PWD##*/}
# get a timestamp
timestamp=$(date +%s)
# create a unique tmp-dir name
tmpdirname="${timestamp}-${currdirname}"
# make a directory in chepec/tmp with the name of the current dir
mkdir /media/bay/taha/chepec/tmp/$tmpdirname
# Copy the contents of the current directory to the tmp/$currdirname directory
cp * -R /media/bay/taha/chepec/tmp/$tmpdirname
# Empty the current directory of all contents
rm * -R # note: hidden files and subdir unaffected
# Return the stuff we want to keep after wipe-dir
# (we are of course assuming that the following 4 file(type)s always exist)
# (if in fact they do not exist, use conditional statements instead (see below)
cp /media/bay/taha/chepec/tmp/$tmpdirname/*.Rnw .
cp /media/bay/taha/chepec/tmp/$tmpdirname/vc .
cp /media/bay/taha/chepec/tmp/$tmpdirname/vc.tex .
cp /media/bay/taha/chepec/tmp/$tmpdirname/vc-git.awk .
## Return stuff that may not always exist (check first...)
## The use of conditionals is mainly to avoid annoying "file does not exist" messages...
# Return *.Rproj file (removal is unnecessary and makes RStudio less useful)
Rprojfiles=`ls -1 /media/bay/taha/chepec/tmp/$tmpdirname/*.Rproj 2>/dev/null | wc -l`
if [ $Rprojfiles != 0 ]; then
cp /media/bay/taha/chepec/tmp/$tmpdirname/*.Rproj .
fi
# Return *.rda files (considering peak-data files, which "cost" a lot to create)
rdafiles=`ls -1 /media/bay/taha/chepec/tmp/$tmpdirname/*.rda 2>/dev/null | wc -l`
if [ $rdafiles != 0 ]; then
cp /media/bay/taha/chepec/tmp/$tmpdirname/*.rda .
fi
# Return *.Rmd files (R markdown source files)
Rmdfiles=`ls -1 /media/bay/taha/chepec/tmp/$tmpdirname/*.Rmd 2>/dev/null | wc -l`
if [ $Rmdfiles != 0 ]; then
cp /media/bay/taha/chepec/tmp/$tmpdirname/*.Rmd .
fi
# Return *.css files (css files) [for sample-matrix]
cssfiles=`ls -1 /media/bay/taha/chepec/tmp/$tmpdirname/*.css 2>/dev/null | wc -l`
if [ $cssfiles != 0 ]; then
cp /media/bay/taha/chepec/tmp/$tmpdirname/*.css .
fi
# Return .knitme file [empty file used to indicate knitr jobs]
knitmefile=`ls -1 /media/bay/taha/chepec/tmp/$tmpdirname/.knitme 2>/dev/null | wc -l`
if [ $knitmefile != 0 ]; then
cp /media/bay/taha/chepec/tmp/$tmpdirname/.knitme .
fi
fi fi
# Return *.Rmd files (R markdown source files)
Rmdfiles=`ls -1 $temp_folder/$tmpdirname/*.Rmd 2>/dev/null | wc -l`
if [ $Rmdfiles != 0 ]; then
cp $temp_folder/$tmpdirname/*.Rmd .
fi
# Return *.css files (css files) [for sample-matrix]
cssfiles=`ls -1 $temp_folder/$tmpdirname/*.css 2>/dev/null | wc -l`
if [ $cssfiles != 0 ]; then
cp $temp_folder/$tmpdirname/*.css .
fi
# Return .knitme file [empty file used to indicate knitr jobs]
knitmefile=`ls -1 $temp_folder/$tmpdirname/.knitme 2>/dev/null | wc -l`
if [ $knitmefile != 0 ]; then
cp $temp_folder/$tmpdirname/.knitme .
fi
fi
echo "Terminating..." die "All done. Exiting..." 0
exit 0
fi
## Here is the wild land of more than one *.Rnw file in current directory
echo "<cheRTeX> This script can be run with one argument is process mode,"
echo "<cheRTeX> or with zero arguments in post-processing mode."
echo "<cheRTeX> Terminating..."
exit 1
fi fi
@ -422,16 +451,16 @@ if (( $runtime > 180 )); then
gotify push --quiet --title "$dir_wd" --priority 5 "chertex.sh $@ \nCompleted in $runtime s" gotify push --quiet --title "$dir_wd" --priority 5 "chertex.sh $@ \nCompleted in $runtime s"
fi fi
echo "-------------------------------------" msg "${On_Cyan}-------------------------------------${NOFORMAT}"
# the padding for runtime makes the formatting work # the padding for runtime makes the formatting work
# three digits for seconds is enough for just above 15 minutes # three digits for seconds is enough for just above 15 minutes
printf "=== chertex.sh completed in %03d s ===\n" $runtime printf "${On_Cyan}=== chertex.sh completed in %03d s ===${NOFORMAT}\n" $runtime 1>&2
if [[ $cetcest == "CET" ]]; then if [[ $cetcest == "CET" ]]; then
echo "=== $(date) ===" msg "${On_Cyan}=== $(date) ===${NOFORMAT}"
else else
echo "=== $(date) ===" msg "${On_Cyan}=== $(date) ===${NOFORMAT}"
fi fi
echo "-------------------------------------" msg "${On_Cyan}-------------------------------------${NOFORMAT}"
simpledelay.sh 3 simpledelay.sh 3
exit 0 exit 0

Loading…
Cancel
Save