Check if VARIABLES are set with Bash

Written by James McDonald

February 9, 2022

I have a script that needs to check if it is called with an environment that contains two variables

  • OPERATOR_ADDRESS
  • DELEGATOR_ADDRESS

if it does not find them it will call a script ./getNodeAddressBech32.sh to set them and continue.

How do you (properly) check for a null or unset variable in bash?

https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02

if [ -z "${OPERATOR_ADDRESS+x}" -o -z "${DELEGATOR_ADDRESS+x}" ]
then
    . ./getNodeAddressBech32.sh
fi
Examples

If OPERATOR_ADDRESS is set and DELEGATOR_ADDRESS is unset it will evaluate to true

OPERATOR_ADDRESS=shareledgervaloper....
echo ${OPERATOR_ADDRESS+x}
# outputs x

# so will evaluate like the following
if [ -z "x" -o -z "" ] # true run the script

If both OPERATOR_ADDRESS and DELEGATOR_ADDRESS are set then the parameter expansion will make it

if [ -z "x" -o -z "x" ] # false because "x" is not zero length for both so skip running the ./getNodeAddressBech32.sh script

0 Comments

Submit a Comment

Your email address will not be published.

You May Also Like…

List your VSCode Extensions

Ever wondered what extensions you have installed and want to keep a list? This actually is a good way to audit your...

array_merge vs the + operator

<?php $options = [ 'rootNode' => 'response' ]; // array_merge // the same key appearing later will overwrite echo...