0

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

2
  • What is the code outputting now? Commented Nov 15, 2016 at 4:16
  • Your script is full of incorrect syntaxes. Commented Nov 15, 2016 at 4:20

1 Answer 1

4

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/

Sign up to request clarification or add additional context in comments.

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.