Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if length of array is equal to a variable in bash

Tags:

bash

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?

like image 980
Krøllebølle Avatar asked Oct 27 '12 15:10

Krøllebølle


People also ask

How do I get the length of an array in bash?

To get the length of an array, we can use the {#array[@]} syntax in bash. The # in the above syntax calculates the array size, without hash # it just returns all elements in the array.

How do you check if a variable is equal in bash?

You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!=

How do I get the length of a variable in bash?

We can use the # operator to get the length of the string in BASH, we need to enclose the variable name enclosed in “{ }” and inside of that, we use the # to get the length of the string variable. Thus, using the “#” operator in BASH, we can get the length of the string variable.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.


1 Answers

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
like image 82
sampson-chen Avatar answered Oct 20 '22 18:10

sampson-chen