0

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 :(

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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= 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.