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