Skip to content

Instantly share code, notes, and snippets.

@keuv-grvl
Last active September 18, 2019 15:14
Show Gist options
  • Save keuv-grvl/c9fffeb44534e0e9eed85e0a207eeb75 to your computer and use it in GitHub Desktop.
Save keuv-grvl/c9fffeb44534e0e9eed85e0a207eeb75 to your computer and use it in GitHub Desktop.
Various tips to write bash scripts
#!/usr/bin/env bash
#-- Set some useful bash options
set -e # this script exits on error
set -o pipefail # a pipeline returns error code if any command fails
set -u # unset variables as an error, and immediately exit
set -x # print each command on STDERR before running it, useful for logging and debugging
set +x # turn off 'set -x'
#-- Handling a fixed list of arguments (which are mandatory)
: ${1? "usage: <name> <age>" }
: ${2? "usage: <name> <age>" }
NAME="$1"
AGE="$2"
echo "Hello $1, or should I say ${NAME}${AGE}YO"
#-- Handling at least 3 mandatory arguments
if [ $# -lt 3 ] ; then
echo "usage: memo.sh <name> <age> <location> [<anything> ...]"
exit 1 # exit status different from 0 indicates abnormal
fi;
# Iterate over arguments
echo "Some info about you:"
for I in "$@" ; do
echo " > $I"
done
#-- Managing options
# from: http://anne.pacalet.fr/Notes/doku.php?id=notes:0157_bash_modele_script
OPTIONS=$(getopt -o hv::m: --long help,verbose::,mode: -- "$@")
if [ $? != 0 ] ; then exit 1 ; fi
eval set -- "$OPTIONS"
MODE="default" # default value
while true; do
case "$1" in
-h | --help ) help ; exit 0 ;;
-v | --verbose )
case "$2" in
"") verbose=1 ; shift 2 ;;
*) verbose=$2 ; shift 2 ;;
esac ;;
-m | --mode ) MODE="$2" ; shift 2 ;;
-- ) shift; break ;;
esac
done
echo "verbose: $VERBOSE"
echo "mode : $MODE"
echo "Remaining arguments: $@"
#-- Wrapper of a Java app
JAR="$HOME/opt/app.jar"
MEM="2G"
java -Xmx$MEM -jar "$JAR" "$@"
# In case I need dependecies within $INSTALL_DIR
INSTALL_DIR="$HOME/opt/"
pushd "$INSTALL_DIR" > /dev/null
java -Xmx$MEM -jar "$INSTALL_DIR/app.jar" "$@"
popd > /dev/null
#-- Execute several commands in parallel and wait for them
[ -f "$FILE1" ] && gzip "$FILE1" &
PID1=$! # store the PID of last background process
[ -f "$FILE2" ] && bzip2 "$FILE2" &
[ -f "$FILE3" ] && zip "$FILE3.zip" "$FILE3" &
# wait for gzip and print something
wait $PID1 && echo "gzip done"
# wait for all
wait
#-- Functions
bar () {
echo "Welcome to the bar function"
echo 'Arguments are in $@'
echo " > $@"
echo "How to extract values ? $1, $2, $3 and so on"
}
bar $(date)
#-- Loops
echo "List executable files within the current directory ('$(pwd)')"
for VAR in $(find . -mindepth 1 -maxdepth 1 -type f -executable) ; do
echo " - $(basename $VAR)"
done;
#-- Auto logging
# STDOUT to terminal and LOGFILE ; STDERR to LOGFILE
LOGFILE="logfile-$(date +"%Y%m%d-%H%M%S").txt"
exec 3<> $LOGFILE
exec 2>&3
exec 1> >(tee -a -i $LOGFILE)
set -x
lsof +D . # writes to STDOUT and STDERR
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment