Jay
Jay

Reputation: 73

pass arguments to shell script that has a switch

I am not sure if switch is the proper terminology as I am new to Unix.

I have a shell script that requires what I call a switch to function properly but I also want to pass arguments:

./scriptname -cm

where if I run just ./scriptname it would fail. But I also want to pass various arguments:

./scriptname -cm arg1 arg2 arg3 arg4

This appears to fail due to the -cm. Normally when I do ./scriptname arg1 arg2 arg3 it will work properly but once I add the switch it fails. Suggestions?

Edit1:

Adding some more relevant code:

./scriptname -cm

will call

scriptname

gencmlicense()
{
echo $2
do stuff
}

gentermlicense()
{
do stuff
}

if [ "$1" = "-cm" ] ; then
    gencmlicense
elif [ "$1" = "-term" ] ; then
    gentermlicense
fi

If I added an argument the echo $2 would not print out the second argument passed.

Upvotes: 0

Views: 2528

Answers (1)

Jens
Jens

Reputation: 72667

If you want to pass arguments from the main script to a function unmodified, use

...
if [ "$1" = "-cm" ] ; then
    gencmlicense "$@"
elif [ "$1" = "-term" ] ; then
    gentermlicense "$@"
fi

The "$@" (with double quotes!) expands to all positional parameters. For more on this, see your shell manual, likely under "Parameter Expansion".

If your functions don't need the first positional parameter, you can shift it away:

if [ "$1" = "-cm" ]; then
    shift
    gencmlicense "$@"
elif [ "$1" = "-term" ]; then
    shift
    gentermlicense "$@"
fi

The professional way of handling options, though, is with the getopts builtin, because it is flexible and extensible, yet compact. This is what I use:

#!/bin/sh
MYNAME=${0##*/}  # Short program name for diagnostic messages.
VERSION='1.0'
PATH="$(/usr/bin/getconf PATH):/usr/local/bin"

usage () {
  cat << EOF

usage: $MYNAME [-hvVx] [-a arg] ...

  Perform nifty operations on objects specified by arguments.

Options:
  -a arg   do something with arg
  -h       display this help text and exit
  -v       verbose mode
  -V       display version and exit
  -x       debug mode with set -x

EOF
  exit $1
}

parse_options () {
  opt_verbose=false
  while getopts :a:hvVx option; do
    case $option in
      (a)  opt_a=$OPTARG;;
      (h)  usage 0;;
      (v)  opt_verbose=true;;
      (V)  echo "version $VERSION"; exit 0;;
      (x)  set -x;;
      (?)  usage 1;;
    esac
  done
}

#-------------------------------------------------------------#
#                     Main script                             #
#-------------------------------------------------------------#

parse_options "$@"
shift $((OPTIND - 1))   # Shift away options and option args.
    ...rest of script here...

Upvotes: 5

Related Questions