0

I'm trying to write a simple function that checks whether a variables is declared and non empty or not.

my_var="dummy_val"

function validate_var(){
        ${1:?"Variable is not set"}
}

validate_var my_var
validate_var my_var2

I get the following error:

script: line n: my_var: command not found

Is there a simple way I could reference the variable from the function argument?

Bogdan Prădatu
  • 325
  • 5
  • 15

2 Answers2

1

Pass the variable by prepending a $. Also I've added an echo (as an example), otherwise your validate_var function tries to execute it's argument:

my_var="dummy_val"

function validate_var(){
        echo ${1:?"Variable is not set"}
}

validate_var $my_var
polo-language
  • 826
  • 5
  • 13
1

This seems to work. It uses the ! variable indirection.

function validate_var(){
    : ${!1:?"$1 is not set"}
}
choroba
  • 231,213
  • 25
  • 204
  • 289