Check if array is empty in bash
Asked Answered
B

2

22

I am trying to see if an array is empty in bash

key=[]
key1=["2014"]

I have tried following ways:

[[ -z "$key" ]] && echo "empty" || echo "not Empty" 
[[ -z "$key1" ]] && echo "empty" || echo "not Empty"

Both return 'not Empty'

[[ $key==[] ]] && echo "empty" || echo "not Empty"
[[ $key1==[] ]] && echo "empty" || echo "not Empty"

Both return empty.

Blucher answered 29/1, 2021 at 15:50 Comment(4)
key=[] isn't an array; it's a regular variable with the value []. Bash doesn't really have empty arrays: it has unset variables (which may or may not have the array attribute set), and it has array variables with one or more values assigned to them.Unhandsome
ahhh, i see. Thank you so much for the comment. I guess this is one of the most important things i should know here @UnhandsomeBlucher
Maybe the question could be fixed, in a way to have a useful question about checking array emptyness, and without causing extra troubleshooting in the array definition itself. So, without example code that indeed does not work and can just create problems for newbies landing here.Donella
@ValerioBozz Perhaps - but it seems that in its current form many people have found this Q&A useful over the years. I'm assuming many people new to bash makes the same mistake as OP so it would be a shame to make that part of the Q&A go away. Also, taking code directly from questions on SO and expecting that code to work is probably not something many people do, new or not.Susie
S
36

As noted by @cheapner in the comments, you are not defining your arrays correctly.

key=()
key1=("2014" "kdjg")

key is here an empty array and key1 has 2 elements.

This then prints the number of elements in the arrays, which is 0 and 2 respectively:

echo "${#key[@]}"
echo "${#key1[@]}"

And this prints empty and not empty respectively:

if (( ${#key[@]} == 0 )); then
    echo empty
fi

if (( ${#key1[@]} != 0 )); then
    echo not empty
fi
Susie answered 29/1, 2021 at 15:57 Comment(15)
If you wish for POSIX friendliness, perhaps [ ${#key[@]} -eq 0 ] since many shells do not support (( arithmetic ))Hufnagel
@Hufnagel But, are there bash versions out there that doesn't? I'm assuming a non-historical bash :-)Susie
As stated -- this consideration is for POSIX compliance, not Bash versions. The construct (( C arithmetic )) is a Bash extension and not POSIX compatible. Korn, sh, others, do not have that. ALL have POSIX comparisons however...Hufnagel
@Hufnagel Yes, ok, I tend to use what I find most convenient in the language I'm programming in at the moment and I rarely/never try to find a common denominator for a set of similar languages and only use that subset of functionality. If I'm using bash, arithmetic expansion is surely going to be used.Susie
see this answer here also, potentially for more compatibilty depending on which shell your using serverfault.com/questions/477503/…Pledgee
@Pledgee That Q&A seems nice, but this question is tagged bash so there is no doubt about which shell that's being used.Susie
@Ted Lyngmo good point. well for me in writing code in bash, but i want it to be as cross compatible as possible incase something unknown changes the code isn't broken. You know how it goes with bash, can get buggy unless you know what your doing. But thanks for the good example!Pledgee
I wonder if the performance of this thing is O(N) since it probably has to calculate the length of the array just to understand whenever it's empty or not. Probably, just checking if it contains at least one non-empty element would be enough. So, the test [ -z "$array" ] has sense to me to return true if the first element is empty. That is also POSIX compliant I guess.Donella
@ValerioBozz "it probably has to calculate the length of the array just to understand whenever it's empty or not" - It doesn't take longer for it to determine if an empty array is empty then for an array with 1000000 elements. I guess in big O notation that would make it O(1).Susie
Any thought about [ -z "$array" ] ? It could be another complementary potential answer in my opinion. Clarifying its meaning and potential pitfalls indeed.Donella
@ValerioBozz [ -z "$array" ] is not testing if an array is empty. Try the two element array array=("" "") which that test will say is empty but ${#array[@]} says there are 2 elements. I don't want an edit that explains the wrongness of OPs original array attempt so I rejected your edit suggestion. I already explain that at the top of the answer. I also do not feel the need the explain that the answer deals with the issue in a bash way since it is a questions tagged bash after all.Susie
I see your point, but please compare the question right now with the answer. I agree with you that it's still useful to somehow clarify that square brackets are wrong and are a common pitfall etc., but now it's a bit confusing in the current exact way. I think a compromise is still possible, unsure how.Donella
@ValerioBozz You"ve now changed the question so that'll force an edit of existing answers. Not good. I explained before that I think this kind of edit is not a good idea since the question in its original form was much apprechiated and it would be a shame to destroy that.Susie
I'm sorry. The edit was proposed ~22 hours ago, alongside its related comment, so, before seeing your kind fast reply #65958133Donella
@ValerioBozz I rejected the suggested edit and also commented on why I think it should not be done 22 hours ago, but apparently others approved it 6 hours ago. It's not easy to see what consequences a suggested edit can have from the the review suggested edits queue tool that we have and I think the approval was a mistake that will make this Q&A less useful in the future than it's proven to be over the last 3 years.Susie
R
0

For plain arrays (not associative arrays) empty check, I simply use:

if [[ -z ${array[@]} ]]; then
    # do something
fi
Rogue answered 20/3 at 16:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.