0

I have a script that takes 3 parameters as input and then continues with the script.I am using getopts to check for parameters passed but i am not able to get the value of the passed parameters inside my script. Can anyone examine this code and suggest how to get the values of the parameters passed inside my script(both inside and outside functions)

while getopts ":s:a:c:" params
do
   case $params in
      s) name="$OPTARG" ;;
      a) value="OPTARG" ;;
      c) file="OPTARG" ;;
      ?) print_usage;;
   esac
done

when i try to access $name,$value and $file my script always prints the help info which i have in my script i.e the print_usage contents

Thanks in advance for the help

noob_coder
  • 749
  • 4
  • 15
  • 35

1 Answers1

0

Aside from the typo (missing $ sign in OPTARG) it works fine for me:

print_usage() {
  echo "usage"
  exit
}

while getopts ":s:a:c:" params
do
   case $params in
      s) name="$OPTARG" ;;
      a) value="$OPTARG" ;;
      c) file="$OPTARG" ;;
      ?) print_usage;;
   esac
done

echo "name=$name, value=$value, file=$file"

Then

$ bash test.sh -s foo -a bar -c baz
name=foo, value=bar, file=baz

and

$ bash test.sh -z 
usage
Alex Harvey
  • 14,494
  • 5
  • 61
  • 97