I am new to shell and I was trying to write a custom function that takes regular arguments, as well as parse any flags provided.
test_it() {
flag1="false"
flag2="false"
while getopts "ab" opt; do
case ${opt} in
a) flag1="true" ;;
b) flag2="true" ;;
*) break ;;
esac
done
echo $flag1 $flag2
shift "$(($OPTIND - 1))"
echo "Custom param: $1"
}
However, this function would only work as I wanted if I supply the custom param after the flags. If I were to supply the custom param before the flags, it doesn't parse the flags.
> test_it -ab foo
true true
Custom param: foo
> test_it foo -ab
false false
Custom param: foo
> test_it -a foo -b
true false
Custom param: foo
Is there a way in which I can make it so that the flags and params get parsed correctly regardless of order? In other words, it should echo true true for both flags in all three of these cases, since they were invoked at some point during the function call? This should be possible, as I have observed functions like rsync to behave that way.
test-- you're overriding the builtin command.