简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM