Search code examples
bashexitgetopts

Why is this simple bash script not working? getopts


I don't get why this won't work as it's really simple.

#!/bin/bash
type='A'

while getopts "t:" OPTION
do
  case $OPTION in
    t)
       echo "The value of -t is $OPTARG"
       type=$OPTARG
       exit
       ;;
    \?)
       echo "Used for the help menu"
       exit
        ;;
  esac
done
echo $type

Output I get:

root@w:/etc/scripts# ./dns_add_record -t test  
The value of -t is test  
root@w:/etc/scripts# ./dns_add_record  
A  

Expected output:

root@w:/etc/scripts# ./dns_add_record -t test  
The value of -t is test  
test

Can someone figure out what is wrong? It's probably something stupid, but I can't get this working the way I want it to.


Solution

  • exit exits from the shell script.

    Remove it from the -t case, it only makes sense for help.


    Adding set -x to your script gives this trace:

    + type=A
    + getopts t: OPTION
    + case $OPTION in
    + echo 'The value of -t is 3'
    The value of -t is 3
    + type=3
    + exit