azatuni
azatuni

Reputation: 43

Looping variables with empty value

I have a some variables

VAR1=1

VAR2=

VAR3=3

I want to pace it through loop & give a null value to those which are empty.

for somevar in $VAR1 $VAR2 $VAR3

do

test -z $somevar && $somevar=null

done

But it is not working :(

Upvotes: 0

Views: 114

Answers (3)

Paul
Paul

Reputation: 7335

I stumbled on this and another Q&A which for which I put a related answer here: https://stackoverflow.com/a/79208087/2816571 . In the specific case of the current question the empty variables need to be quoted in the bash loop to be iterated over:

z=
for value in $z; do echo "value=${value}"; done  #outputs nothing e.g. loop body is not executed
for value in "$z"; do echo "value=${value}"; done #outputs value= 

Upvotes: 0

konsolebox
konsolebox

Reputation: 75588

If you want to set the variable with a literal string 'null' you can do:

for somevar in VAR1 VAR2 VAR3; do
    [[ -z ${!somevar} ]] && eval "${somevar}=null"
done

That's safe. Just make sure that the variable names are valid.

Upvotes: 0

pgl
pgl

Reputation: 8031

Probably the easiest way to do this is to assign a default value to each variable. eg:

${VAR:=value}

This sets the value of $VAR to "value" if it's unset or null.

To answer your specific question about why your code isn't working, it's probably because you're doing

$somevar=null

rather than:

somevar=null

Upvotes: 2

Related Questions