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?

2

2 Answers 2

1

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

function validate_var(){
    : ${!1:?"$1 is not set"}
}
Sign up to request clarification or add additional context in comments.

2 Comments

If var is set to empty string, it shows bash: !1: var is not set
I don't know what the expected output is for that case. Maybe validate the input first.
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

5 Comments

With this solution I get "invalid variable name", even if the variable is declared as empty string (e.g. my_var2="").
Also, this passes "dummy_val" to the function, instead of "my_var".
It seems to work fine with an empty string: $ my_var2="" $ validate_var $my_var2 bash: 1: Variable is not set
You mean you want to pass a variable by reference?
Actually, you're right. It does work, I don't know what I was doing wrong. Anyway, @choroba's answer does exactly what I want. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.