'How do you compare the value of an array to a variable in bash script?

I'm practicing bash and honestly, it is pretty fun. However, I'm trying to write a program that compares an array's value to a variable and if they are the same then it should print the array's value with an asterisk to the left of it.

#!/bin/bash

color[0]=red
color[1]=blue
color[2]=black
color[3]=brown
color[4]=yellow
favorite="black"

for i in {0..4};do echo ${color[$i]};
if {"$favorite"=$color[i]}; then
    echo"* $color[i]"
done

output should be *black



Solution 1:[1]

There's few incorrect statements in your code that prevent it from doing what you ask it to. The comparison in bash is done withing square brackets, leaving space around them. You correctly use the = for string comparison, but should enclose in " the string variable. Also, while you correctly address the element array in the echo statement, you don't do so inside the comparison, where it should read ${color[$i]} as well. Same error in the asterisk print. So, here a reworked code with the fixes, but read more below.

#!/bin/bash

color[0]=red
color[1]=blue
color[2]=black
color[3]=brown
color[4]=yellow
favorite=black
for i in {0..4};do
   echo ${color[$i]};
   if [ "$favorite" = "${color[$i]}" ]; then
      echo "* ${color[$i]}"
   fi
done

While that code works now, few things that probably I like and would suggest (open to more expert input of course by the SO community): always enclose strings in ", as it makes evident it is a string variable; when looping an array, no need to use index variables; enclose variables always within ${}. So my version of the same code would be:

#!/bin/bash
color=("red" "blue" "black" "brown" "yellow")
favorite="black"
for item in ${color[@]}; do
   echo ${item}
   if [ "${item}" = "${favorite}" ]; then
     echo "* $item"
   fi
done

And a pointer to the great Advanced Bash-Scripting Guide here: http://tldp.org/LDP/abs/html/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1