Have written two ways, trying to parse short and long options by hand. The first is complicated with the use of IFS=" ="
. Perhaps set -- $*
is not necessary.
rando ()
{
IFSPREV="$IFS" # Save IFS (splits arguments on whitespace by default)
IFS=" =" # Split arguments on " " and "="
set -- $* # Set positional parameters to command line arguments
IFS="$IFSPREV" # Set original IFS
local iarg=0 narg="$#"
while (( narg > 0 )); do
opt="$1"
iarg=$(( iarg + 1 ))
case $opt in
("-s"|"--src"|"--source") src="$2" ; shift 2 ;;
("-d"|"--dst"|"--destin") dst="$2" ; shift 2 ;;
("--") shift 1 ; break ;;
("-"*) printf '%s\n' "Unknown option: $1" ; shift 1 ;;
(*) shift 1 ; break ;;
esac
done
}
And here is the other, but I also want to split on =
for long-options.
rando ()
{
PARAMS=""
while (( "$#" )); do
case "$1" in
("-s"|"--src"|"--source")
if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
src="$2"
shift 2
else
echo "Error: Argument for $1 is missing" >&2
exit 1
fi
;;
("-d"|"--dst"|"--destin")
if [ -n "$2" ] && [ ${2:0:1} != "-" ]; then
dst="$2"
shift 2
else
echo "Error: Argument for $1 is missing" >&2
exit 1
fi
;;
-*|--*=) # unsupported flags
echo "Error: Unsupported flag $1" >&2
exit 1
;;
*) # preserve positional arguments
PARAMS="$PARAMS $1"
shift
;;
esac
done
}