Reputation: 344
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?
Upvotes: 0
Views: 361
Reputation: 241828
This seems to work. It uses the !
variable indirection.
function validate_var(){
: ${!1:?"$1 is not set"}
}
Upvotes: 1
Reputation: 846
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
Upvotes: 1