I have an array of options and their arguments:
ARGS=('-a' '-c' 'red' 'orange' '--verbose' '-p' 'apple' 'banana')
I need to extract arguments for the option -c and get a list of the rest:
echo "${COLORS[@]}" # returns: red orange
echo "${OPTIONS[@]}" # returns: -a --verbose -p apple banana
I have managed to get a list of colors using getopts (probably not the best approach), but I didn't find a way to extract the rest of the options.
COLORS=()
set_colors() {
while getopts "p:" option 2>/dev/null; do
case ${option} in
p)
COLORS+=("$OPTARG")
while [[ "$OPTIND" -le "$#" ]] && [[ "${!OPTIND:0:1}" != "-" ]]; do
COLORS+=("${!OPTIND}")
((OPTIND++))
done
;;
*) ;;
esac
done
}
set_colors "${ARGS[@]}"
-a -c red -c orange --verbose -p apply -p banana- ie. the-cflag is cumulative and needs to be specified for each color. This will make parsing arguments easier and more consistent for a small inconvenience.