Bash: How to detect "repeat" flag, such as -vvv?

Viewed 95

Currently, I have some flag -x, along with some others:

while getopts abcx opt; do
  case $opt in
    a) a=true; ;;
    b) b=true; ;;
    c) c=true; ;;
    x) x=true; ;;
  esac
done

However, I want to make it so that adding an x will increase the level of the flag. I've seen this with v for verbose with extra v's increasing the verbosity. How do I detect this in my Bash script?

1 Answers

I want to make it so that adding an x will increase the level of the flag.

Use a counter:

unset a b c x
while getopts abcx opt; do
  case $opt in
    a) a=true; ;;
    b) b=true; ;;
    c) c=true; ;;
    x) ((x++)); ;;
  esac
done
echo "x=$x"

Then use it as:

bash optscript.sh -abcxxx
x=3
Related