I've been reading about getopt and getopts but it doesn't seem like it's possible to parse arguments like --foo or even -foo. I've started my own script trying to achieve this, but I'm still wondering if I'm losing performance and if there is a better way to do this task.
Also I'm using the [[ =~ ]] regex syntax which seems to be available only in newer bash versions, should it be a big issue?
My bash version: GNU bash, version 4.1.7(2)-release (x86_64-unknown-linux-gnu)
My scripts goes as follows
Code:
#!/bin/bash
if [ $# -eq 0 ]; then
printf "You need to give arguments!!!\n" >&2
exit 1
fi
SKIP=0
for arg in "$@"; do
[ $SKIP -eq 1 ] && SKIP=0 && continue
if [[ $arg =~ ^--foo=.*$ ]]; then
printf "foo = %s\n" "${arg/#*=/}"
shift
elif [[ $arg =~ ^--config=.*$ ]]; then
printf "config = %s\n" "${arg/#*=/}"
shift
elif [[ $arg =~ ^--bar$ ]]; then
shift
[ -z "$1" -o "${1/%[^-]*/}" = "--" ] && printf "No argument for bar\n" >&2 && break
printf "bar = %s\n" "$1"
shift
# Skip next one
SKIP=1
elif [[ $arg =~ ^-a$ ]]; then
shift
[ -z "$1" -o "${1/%[^-]*/}" = "--" ] && printf "No argument for -a\n" >&2 && break
printf "a = %s\n" "$1"
shift
SKIP=1
elif [[ $arg =~ ^--playlist=.+$ ]]; then
printf "playlist = %s\n" "${arg/#*=/}"
shift
else
if [[ $arg =~ ^--.*$ ]]; then
printf "Unknown option\n" >&2
else
printf "Regular argument = %s\n" "$arg"
fi
shift
fi
done
When running it like this
./argument_test.sh dontuse --foo="test" normal --config="s.xml" --bar "something" --playlist="playlist.txt" -a
This is what I get as output, which I think should be the correct thing.
Regular argument = dontuse
foo = test
Regular argument = normal
config = s.xml
bar = something
playlist = playlist.txt
No argument for -a
Edit: note that --bar doesn't use the equals sign, which means it has to use the next argument in line