I have an array of variables. I want to check if the variables have a value using the for loop.
I am getting the values into loop but the if condition is failing
function check {
arr=("$@")
for var in "${arr[@]}"; do
if [ -z $var ] ; then
echo $var "is not available"
else
echo $var "is available"
fi
done
}
name="abc"
city="xyz"
arr=(name city state country)
check ${arr[@]}
For the above I am getting all as available
Expected output is
name is available
city is available
state is not available
country is not available
varin your loop takes on the values name, city, state and country. [ -z ... ] tests whether the length of the argument is zero. None of those words has zero length, so theelsebranch is taken every time.