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?
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.
You can check the equality and inequality of two strings in bash by using if statement. “==” is used to check equality and “!=
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.
$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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With