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

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


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.


You can set a default value for a variable like so:

somecommand.sh

#!/usr/bin/env bashARG1=${1:-foo}ARG2=${2:-bar}ARG3=${3:-1}ARG4=${4:-$(date)}echo "$ARG1"echo "$ARG2"echo "$ARG3"echo "$ARG4"

Here are some examples of how this works:

$ ./somecommand.shfoobar1Thu Mar 29 10:03:20 ADT 2018$ ./somecommand.sh ezezbar1Thu Mar 29 10:03:40 ADT 2018$ ./somecommand.sh able was iablewasiThu Mar 29 10:03:54 ADT 2018$ ./somecommand.sh "able was i"able was ibar1Thu Mar 29 10:04:01 ADT 2018$ ./somecommand.sh "able was i" superable was isuper1Thu Mar 29 10:04:10 ADT 2018$ ./somecommand.sh "" "super duper"foosuper duper1Thu Mar 29 10:05:04 ADT 2018$ ./somecommand.sh "" "super duper" hi youfoosuper duperhiyou


if [ ! -z $1 ] then     : # $1 was givenelse    : # $1 was not givenfi