Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ] 
like image 772
Abe Avatar asked Feb 17 '12 17:02

Abe


People also ask

How do you indicate optional arguments?

To indicate optional arguments, Square brackets are commonly used, and can also be used to group parameters that must be specified together. To indicate required arguments, Angled brackets are commonly used, following the same grouping conventions as square brackets.

How do you pass input arguments in shell script?

Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.


2 Answers

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.

like image 112
Itay Perl Avatar answered Sep 22 '22 18:09

Itay Perl


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

somecommand.sh

#!/usr/bin/env bash  ARG1=${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.sh foo bar 1 Thu Mar 29 10:03:20 ADT 2018  $ ./somecommand.sh ez ez bar 1 Thu Mar 29 10:03:40 ADT 2018  $ ./somecommand.sh able was i able was i Thu Mar 29 10:03:54 ADT 2018  $ ./somecommand.sh "able was i" able was i bar 1 Thu Mar 29 10:04:01 ADT 2018  $ ./somecommand.sh "able was i" super able was i super 1 Thu Mar 29 10:04:10 ADT 2018  $ ./somecommand.sh "" "super duper" foo super duper 1 Thu Mar 29 10:05:04 ADT 2018  $ ./somecommand.sh "" "super duper" hi you foo super duper hi you 
like image 42
Brad Parks Avatar answered Sep 19 '22 18:09

Brad Parks