Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

sh

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?

like image 552
Francis Lewis Avatar asked Feb 26 '14 18:02

Francis Lewis


1 Answers

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
like image 137
anubhava Avatar answered Sep 28 '22 10:09

anubhava