2

I have written below code for using long options with getopts, but it doesn't work (arguments have no effect on values of the variables). What is the correct syntax?

while getopts "c:(mode)d:(file1)e:(file2)" opt; do
  case $opt in
  -c|--mode)
      mode=$OPTARG
      ;;  
  -d|--file1)
      file1=$OPTARG
      ;;  
  -e|--file2)
      file2=$OPTARG
      ;;  
  esac
done
user13107
  • 3,239
  • 4
  • 34
  • 54
  • possible duplicate of [Using getopts in bash shell script to get long and short command line options](http://stackoverflow.com/questions/402377/using-getopts-in-bash-shell-script-to-get-long-and-short-command-line-options) – oz123 Feb 06 '14 at 09:35

1 Answers1

9

I found that the code in question is for ksh and not bash. For getopts we can't use long options. I ended up manually parsing arguments as below

while test -n "$1"; do
    case "$1" in
      -c|--mode)
          mode=$2
          shift 2
          ;;  
      -d|--file1)
          file1=$2
          shift 2
          ;;  
      -e|--file2)
          file2=$2
          shift 2
          ;;  
    esac
done 
user13107
  • 3,239
  • 4
  • 34
  • 54
  • 2
    Actually, that's how I do it all the time; I typically have a `*)` case which leaves the loop, so arguments can be parsed after the options. – Alfe Feb 06 '14 at 09:59