Empty $OPTARG with getopts "b:" and ''./script -b foo''

bash, sh, shell

Solution

You're missing a colon after `b` (not needed before `b`).

Use this script:

#!/bin/bash

while getopts "b:" opt; do
  case $opt in
    b)  
        echo "result is: $OPTARG";;
    *) 
        echo "Invalid option: -$OPTARG" >&2;;  
  esac
done

Problem

I'm trying to create a bash file that will accept command line parameters, but my OPTARG isn't producing any result, which it appears is necessary to get this to work? Here is what I have: ``` #!/bin/bash while getopts ":b" opt; do case $opt in b) echo "result is: $OPTARG";; \?) echo "Invalid option: -$OPTARG" >&2;; esac done ``` When I run that with: `file.sh -b TEST`, this is the result I get: `result is:` Any ideas what is going on here?

Original source