13

I want to check if the length of a bash array is equal to a bash variable (int) or not. My current code looks like this:

if [ "${#selected_columns}" -eq "${number_of_columns}" ]; then
    echo "They are equal!"
fi

This returns false since the echo statement is never run. However, doing this produces 4 for both of them:

echo "${#selected_columns[@]}"
echo "${number_of_columns}"

What's wrong here? Has it something to do with string versus int?

2
  • 6
    Aren't you missing [@] in the first example? Commented Oct 27, 2012 at 15:44
  • if [ "${#selected_columns[@]}" -eq "${number_of_columns}" ]; then Commented Oct 27, 2012 at 15:44

2 Answers 2

19

In your:

if [ "${#selected_columns}" -eq "${number_of_columns}" ]; then
    echo "They are equal!"
fi

${#selected_columns} is missing [@].

Fixed:

if [ "${#selected_columns[@]}" -eq "${number_of_columns}" ]; then
    echo "They are equal!"
fi
Sign up to request clarification or add additional context in comments.

3 Comments

Except why didn't you just reply with an answer? StackOverflow is about answering questions for the benefit of other people in addition to the original asker. Someone may not read the comments under a question and just leave without learning anything new, after seeing that there are no answers yet submitted. (I missed your comment until I was half-way typing out the solution) Move your comment to an answer and I'll upvote you, if you'd like.
I think you feel strongly about this issue: so why not post your comment as an answer, I'll remove my own answer if that makes you happy? =)
Nah, you already did the dirty work. Now it's easier to see what was wrong ;)
6

According to bash's man page:

${#name[subscript]} expands to the length of ${name[subscript]}. If subscript is * or @, the expansion is the number of elements in the array. Referencing an array variable without a subscript is equivalent to referencing the array with a subscript of 0.

Using ${name} on index arrays will result to ${name[0]}, then you got the length of ${name[0]}, not counting elements of whole array. So that's not problem about comparing string with integer. AFAIK, comparing "integer number in string" with "integer assigned by let" is never a problem in bash scripting.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.