2

I have written some script in bash but it won't work. Can anybody help me with this. I am providing the script here:

#!/bin/bash
declare -a array=("red" "blue" "green" "yellow")

for (( i=0; i<${array[@]}; i++));
do
        echo "items: $i"
done

I want to iterate through the array. Coz when ever I do it I'm getting an error saying:: arr1.sh: 2: Syntax error: "(" unexpected

3
  • Use ${#array[@]} inside the (( )) Commented Nov 19, 2021 at 11:25
  • Sure you're using bash to execute your script and not sh? Commented Nov 19, 2021 at 11:43
  • Check this comment about "'s around the array syntax Commented Nov 19, 2021 at 14:46

1 Answer 1

7

Try this:

$ cat iterate_array.sh 
#!/bin/bash
declare -a array=("red" "blue" "green" "yellow")
for  i in ${!array[@]}; do
        echo ${array[$i]}
done
$ ./iterate_array.sh 
red
blue
green
yellow

Is that what you want?

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.