Shell – Optional arguments after or before the mandatory arguments

argumentsoptionsshellshell-script

I'm creating a shell script and I need it to take two mandatory arguments and one optional. How do I check that? In most scripts I've seen, the optional arguments are passed before the mandatory ones, like:

cut -c2 test.txt

But for me this pattern would be complicated to check in the script, so my idea is to consider the third argument as optional.

Best Answer

If you're fine with the optional arguments being at the end, you can just do this:

foo=$1
bar=$2
baz=${3:-default value}

That will store the first two arguments in $foo and $bar. If a third argument was provided, it will be stored in $baz; otherwise it will default to default value. You can also just check if the third variable is empty:

if [ -z "$3" ]; then
    # Code for the case that the user didn't pass a third argument
fi

If you want the defaults at the beginning, the easiest way is probably to check the number of arguments passed to the script, which is stored in $#. For example:

case $# in
  2)
    # Put commands here for when the user passes two arguments
    # Could just be setting variables like above, or anything else you need
    ;;
  3)
    # Put commands here for when the user passes three arguments
    ;;
  *)
    echo "Wrong number of arguments passed"
    exit 1;;
esac

Switching on $# will work fine for either case, if you want error checking. If your script uses getopt-style arguments like the cut example, you could use that; see this Stack Overflow question for more information

Related Question