0

Suppose I have a bash script scr.sh. Inside this script I have a variable $x. I need to setup the following behavior. If scr.sh is called with an argument, as in:

./scr.sh 45

then I want x to be assigned to this value inside my bash script. Otherwise, if there is no command line argument, as in:

./scr.sh

x should be assigned to some default value, which in my case is an environment variable, say x=$ENVIRONMENT_VAR.

How can I do this?

a06e
  • 18,594
  • 33
  • 93
  • 169

2 Answers2

4

You can use this to set a default value:

x="${1:-$ENVIRONMENT_VAR}"

${parameter:-word}
   Use Default Values. If parameter is unset or null, the expansion of word is
   substituted. Otherwise, the value of parameter is substituted.
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • 2
    I wish more people understood how powerful the `${parameter:[-+?=]word}` paradigm is. Good luck to all. – shellter Oct 21 '14 at 13:11
  • @shellter Is there a link where `${parameter:[-+?=]word}` is explained? – a06e Oct 21 '14 at 13:12
  • 1
    @becko : `http://tldp.org/LDP/abs/html/parameter-substitution.html` is the best I know of. Good luck to all. – shellter Oct 21 '14 at 13:16
  • 1
    You want to use `${1-$ENVIRONMENT_VAR}` in case the empty string (`./scr.sh ""`) is a valid argument that should not be replaced with the value of `ENVIRONMENT_VAR`. – chepner Oct 21 '14 at 14:39
  • @becko They are all documented in the man page, under Parameter Expansion. – chepner Oct 21 '14 at 15:08
0

While this has been answered perfectly well by @Cyrus, I'd like to offer a slight variation of the ${parameter:-word} approach, namely:

: ${x:=${1-$ENVIRONMENT_VAR}}

This allows you to go one step further and submit an override functionality on calling the script. Below you see the three invariants one can have using this approach:

$ ./src.sh
x=42
$ ./src.sh 8
x=8
$ x=2 ./src.sh 8
x=2

The script used for the above output:

$ cat ./src.sh
#!/usr/bin/env bash

ENVIRONMENT_VAR=42
: ${x:=${1-$ENVIRONMENT_VAR}}
echo "x=${x}"
ikaerom
  • 538
  • 5
  • 27