Eeel
Eeel

Reputation: 127

for loop to check multiple var to return the name of empty var

i'm writing a bash script, i have a list of var

var1="chicken"
var2="sweet potatoe"
var3=""
var4="rice"

And i want to return the name of the var itself which is empty

for var in var1 var2 var3 var4; do
    if [[ ! -n "$var" ]]; then
    echo "Fix that: $var ${!var}"
    fi
done

this return nothing.

the opposite works

for var in var1 var2 var3 var4; do
    if [[ -n "$var" ]]; then
    echo "Fix that: $var ${!var}"
    fi
done

I have tested several way to achieve this, i want to keep it very simple, i can't figure it out.

Thanks for help.

Upvotes: 2

Views: 59

Answers (1)

glenn jackman
glenn jackman

Reputation: 247012

use variable indirection:

for var in var1 var2 var3 var4; do
    [[ -z ${!var} ]] && echo empty: $var
done
empty: var3

Upvotes: 3

Related Questions