0

How do I take optional parameters in my shell script.

Command Line argument would be: ./abc.sh parm1 parm2 parm3 parm4

Here parm3 and parm4 are optional depending upon parm1(config)

How to write a shell script which will take mandatorily parm1 and parm2 as argument and treat the other two as optional parameters

3
  • I am new to shell and handling this scenario for the first time. Commented Sep 1, 2015 at 5:17
  • Don't forget to reject ./abc.sh p1 p2 p3 p4 p5 if, as your question indicates, only 2, 3 or 4 arguments are acceptable. You should know about $#, the special parameter (variable) that reports the number 'command line arguments' ('positional parameters' in the formal jargon). Commented Sep 1, 2015 at 6:12
  • No this is not a duplicate as this question is at its core about mandatory parameters (despite the title) whereas the other is about optional ones. Commented May 1, 2019 at 2:27

1 Answer 1

0

Use ${var?} syntax for required parameters:

#!/bin/sh : ${1:?first argument is required} : ${2:?second argument is required} 

You can check the number of argument with $#, so you can do things like:

#!/bin/sh die() { echo "$@" >&2; exit 1; } case ${1?} in foo) test $# = 4 || die When first argument is foo, you must give 4 args;; bar) test $# = 2 || die When first argument is bar, only give 2 args;; *) ;; esac 
Sign up to request clarification or add additional context in comments.

6 Comments

test -n "$3" will pass if the empty string is passed as an argument, so checking $# is the only way to handle optional values that could be empty.
Is there a reason you chose not to quote the arguments? That is, as you indicated, bad general practice and doesn't help clarify anything here.
I'd use : ${1?first arg is required} to display an error only if the parameter is missing altogether. Use : ${1:?...} if a null string is not permitted as the value of the argument.
@chepner: test -n "$3" fails when $3 is the empty string, and I'm making the tacit assumption that the empty string is unacceptable throughout.
@Etan I think the code is cleaner without quotes, and I'm being meticulous in using them where necessary. The only impact is in the possible difference with echo, and those statements are debug in nature and don't really impact anything. I believe that overquoting is as much of a problem as underquoting, and leads to a failure to learn when quotes are required and how they are used, so I err on the side of underquoting in answers on this forum. And now the echos with unquoted arguments have been removed, so that point is moot!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.