0

Please consider the following Bash function.

#!/bin/bash

function assert_var(){
  echo "check if variable with name $1 exists"
  if [ -z $1 ];then
    echo "EXISTS!"
  else
    echo "NOT EXISTS!"
  fi
}


export FOO="123"
assert_var "FOO"
assert_var "BAR"

The expectation is that variable FOO should be detected and absence of BAR as well. For that, I need somehow to pass and use the variable name as argument to the function.

How to do that properly?

Open Food Broker
  • 1,095
  • 1
  • 8
  • 31
  • 4
    and https://stackoverflow.com/questions/44221093/bash-function-to-check-if-a-given-variable-is-set/44221215 – KamilCuk Jul 01 '20 at 13:47
  • Be sure to use `-v`, though. The more upvoted duplicate is old and has more upvotes for answers that predate `-v`. – chepner Jul 01 '20 at 14:16

1 Answers1

2

This function should do the job for you:

assert_var() {
   if [[ -z ${!1+x} ]]; then
      echo 'NOT EXISTS!'
   else
      echo 'EXISTS!'
   fi
}

Changes are:

  • Use ${var+x} to check if a variable is unset. ${var+x} is a parameter expansion that evaluates to nothing if var is unset, and substitutes the string x otherwise. More details here.
  • Use indirect referencing of variable by name i.e. ${!1+x} instead of ${1+x}
  • Use single quotes when you are using ! in string to avoid history expansion

Testing:

FOO='123'
assert_var "FOO"
EXISTS!
assert_var "BAR"
NOT EXISTS!
anubhava
  • 761,203
  • 64
  • 569
  • 643