Search code examples
bashcommand-line-argumentsargument-passing

How to bypass an optional argument for the following argument in bash?


TABLE=`echo "${1}" | tr '[:upper:]' '[:lower:]'`
if [ $1 = -d ]
   then TABLE=daminundation
elif [ $1 = -b ]
   then TABLE=burnscararea
elif [ $1 = -r ]
   then TABLE=riverpointinundation
elif [ $1 = " " ]
   then echo "User must input -d (daminundation), -b (burnscararea) 
   or -r (riverpointinundation)."
fi
SHAPEFILEPATH=${2}
MERGEDFILENAME=${3}
if [ -z $3 ] ; 
  then MERGEDFILENAME=merged.shp
else
  MERGEDFILENAME=${3}
fi
COLUMNNAME=${4}
if [ -n $4 ]
  then COLUMNNAME=$4
fi

$3 & $4 are optional arguments. However, if I choose not to use $3 but I want to use $4, it will read the command as $3. Confused by other methods, how should I make it so that an undesired optional command can be bypassed for the next one?


Solution

  • You probably want this:

    #!/bin/bash
    
    while getopts ":b :d :r" opt; do
      case $opt in
        b)
          TABLE=burnscararea
          ;;
        d)
          TABLE=daminundation
          ;;
        r)
          TABLE=riverpointinundation
          ;;
        \?)
          echo "Invalid option: -$OPTARG" >&2
          exit 1
          ;;
      esac
    done
    
    shift $((OPTIND-1))
    
    [ -z "$TABLE" ] && ( echo "At least one of -b/-d/-r options must be provided"; exit 1; )
    [ $# -ne 3 ] && ( echo "3 params expected!"; exit 1; )
    SHAPEFILEPATH="$2"
    MERGEDFILENAME="$3"
    COLUMNNAME="$4"
    # other stuff