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

I am trying to create a bash file that will accept command line parameters, but my OPTARG does not produce any result which, in his opinion, is necessary to make this 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 this with:, file.sh -b TESTthis is the result I get:result is:

Any ideas on what's going on here?

+4
source share
1 answer

You are missing a colon after b(not required 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
+9
source

Source: https://habr.com/ru/post/1529046/


All Articles