How to write a bash script that takes optional input arguments?

Abe picture Abe · Feb 17, 2012 · Viewed 277.2k times · Source

I want my script to be able to take an optional input,

e.g. currently my script is

#!/bin/bash
somecommand foo

but I would like it to say:

#!/bin/bash
somecommand  [ if $1 exists, $1, else, foo ]

Answer

Itay Perl picture Itay Perl · Feb 17, 2012

You could use the default-value syntax:

somecommand ${1:-foo}

The above will, as described in Bash Reference Manual - 3.5.3 Shell Parameter Expansion [emphasis mine]:

If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

If you only want to substitute a default value if the parameter is unset (but not if it's null, e.g. not if it's an empty string), use this syntax instead:

somecommand ${1-foo}

Again from Bash Reference Manual - 3.5.3 Shell Parameter Expansion:

Omitting the colon results in a test only for a parameter that is unset. Put another way, if the colon is included, the operator tests for both parameter’s existence and that its value is not null; if the colon is omitted, the operator tests only for existence.