Home > database >  Bash reference variable by string name
Bash reference variable by string name

Time:12-22

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?

CodePudding user response:

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

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

CodePudding user response:

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
  •  Tags:  
  • bash
  • Related