Tuesday, June 5, 2018

Bash - get flags and arbitrary strings in no particular order


#!/bin/bash

# Get arguments and separate them to flags and arbitrary strings
# Execution example: ./get_opts.sh Something -w 10 somethingElse -c20 whatever

# For debug purpose, show everything we received:
# echo $@

# Save original arguments for later use / debug purpose
original_arguments="$@"

# Initialize variable
strings=""

# While there are arguments, keep looping
while (( "$#" )); do
case "$1" in
# if the next argument begins with '-w'
-w*)
# Put all the digits in this or the next argument in  the variable 'warn' and shift the argument array
warn=$(echo $1|tr -cd  '[[:digit:]]')
if [ "$warn" ]; then shift 1;
else warn=$(echo $2|tr -cd  '[[:digit:]]'); shift 2;
fi
;;
# if the next argument beings with '-c'
-c*)
# put all the digits in this or the next argument in the variable 'crit' and shift the argument array
crit=$(echo $1|tr -cd  '[[:digit:]]')
if [ "$crit" ]; then shift 1;
else crit=$(echo $2|tr -cd  '[[:digit:]]'); shift 2;
fi
;;
*)
# Arbitrary strings go here
strings="${strings} $1"
shift
;;
esac
done
echo Warn=${warn} Crit=${crit} Arbitary strings=${strings}
exit