0

I can check if variable is empty:

var=("")

if [[ -z "${var}" ]];
then
    echo "variable is empty"
else
    echo "variable is not empty"
fi

Output:

variable is empty

But when I try to apply it to an element in an array, I get no output:

array=("")

for i in ${array[@]}
do
    if [[ -z "${i}" ]];
    then
        echo "element in array is empty"
    else
        echo "element in array is not empty"
    fi
done
PesaThe
  • 7,259
  • 1
  • 19
  • 43
NZL
  • 71
  • 1
  • 7
  • 2
    Since you don't double quote the `${array[@]}`, it is a subject to word-splitting and your loop does not iterate at all. Double quote it. – PesaThe Jan 23 '19 at 13:06

1 Answers1

0

since there is no element it doesn't get into the for loop. That is why no output is written to stdout.

think this like:

while(there is record)
   loop

since you don't have record in your array, It directly exits

Check this code

array=("1" "2" "" "3")

for i in "${array[@]}"
do
    if [[ -z "${i}" ]];
    then
        echo "element in array is empty"
    else
        echo "element in array is not empty : $i"
    fi
done

Fiddle

Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72
  • thanks, but even if I add some elements is to the array , it still does not recognize empty element. for example: array=("a " " " "c") for i in ${array[@]} do echo ${i} if [[ -z "${i}" ]]; then echo "element in array is empty" else echo "element in array is not empty" fi done – NZL Jan 23 '19 at 13:50
  • check my edited answer please – Derviş Kayımbaşıoğlu Jan 23 '19 at 14:01
  • got it, I had to add double quotes to the array, thanks :)! – NZL Jan 23 '19 at 14:11
  • If this answer is usefull for you please consider to upvote and/or mark it as answer. Thank you – Derviş Kayımbaşıoğlu Jan 23 '19 at 15:37
  • Actually, if the OP accepts this answer, the question can't be [deleted automatically](/help/roomba) so I'm a bit divided here. It would be nice if you were rewarded for your effort, but it would also be nice if this 7.3E+05:th duplicate of this common FAQ could be removed from Stack Overflow. – tripleee Jan 24 '19 at 05:36
  • @tripleee, I just wanted to help. Of course I will be happy if my answer is rewarded with accepted answer or up-vote. However OP is not around here I believe. If the post needed to be deleted, this won't be problem anymore – Derviş Kayımbaşıoğlu Jan 24 '19 at 10:37