iverson iverson - 4 months ago 13
Bash Question

Optional option argument with getopts

while getopts "hd:R:" arg; do
case $arg in
h)
echo "usgae"
;;
d)
dir=$OPTARG
;;
R)
if [[ $OPTARG =~ ^[0-9]+$ ]];then
level=$OPTARG
else
level=1
fi
;;
\?)
echo "WRONG" >&2
;;
esac
done



  • level refers to parameter of -R, dir refers to parameters of -d

  • when I input
    ./count.sh -R 1 -d test/
    it works rightly

  • when I input
    ./count.sh -d test/ -R 1
    it works rightly

  • but I want to make it work when I input
    ./count.sh -d test/ -R
    or
    ./count.sh -R -d test/



This means that I want -R has a default value and the sequence of command could be more flexible.

Answer

getopts doesn't really support this; but it's not hard to write your own replacement.

while true; do
    case $1 in
      -R) level=1
            shift
            case $1 in
              *[!0-9]* | "") ;;
              *) level=$1; shift ;;
            esac ;;
        # ... Other options ...
        -*) echo "$0: Unrecognized option $1" >&2
            exit 2;;
        *) break ;;
    esac
done
Comments