a06e
a06e

Reputation: 20774

How to know if an argument was passed to my bash script?

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?

Upvotes: 0

Views: 337

Answers (2)

ikaerom
ikaerom

Reputation: 727

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}"

Upvotes: 0

Cyrus
Cyrus

Reputation: 88563

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.

Upvotes: 4

Related Questions