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?

2
  • 4
    and stackoverflow.com/questions/44221093/… Commented Jul 1, 2020 at 13:47
  • Be sure to use -v, though. The more upvoted duplicate is old and has more upvotes for answers that predate -v. Commented Jul 1, 2020 at 14:16

1 Answer 1

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!
Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain what ${!1+x} is doing?
yes I just added

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.