0

I have a script that I want to run in three ways:

  1. Without a flag -- ./script.sh
  2. With a flag but no parameter -- ./script.sh -u
  3. With a flag that takes a parameter -- ./script.sh -u username

Is there a way to do this?

After reading some guides (examples here and here) it doesn't seem like this is a possibility, especially if I want to use getopts.

Can I do this with getopts or will I need to parse my options another way? My goal is to continue using getopts if I can.

Wimateeka
  • 2,474
  • 2
  • 16
  • 32

1 Answers1

0

The non-getopts example in BashFAQ #35 can cover the use case:

user_set=0  # 1 if any -u is given
user=       # set to specific string for -u, if provided
while :; do
  case $1 in
    -u=*) user_set=1; user=${1#*=} ;;
    -u)   user_set=1
          if [ -n "$2" ]; then
            user=$2
            shift
          fi ;;
    --)   shift; break ;;
    *)    break ;;
  esac
  shift
done
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441