0

I'm trying to make an array in a bash script. I keep running into a problem even though I feel like I've followed tutorials correctly.

#!/bin/bash
myArray=("cat" "dog" "mouse" "frog")

for i in ${!myArray[@]}; do
  echo "element $i is ${myArray[$i]}"
done

Running this, produces: bash_array.sh: 2: Syntax error: "(" unexpected

I found another tutorial which uses declare -a myArray=("cat" "dog" "mouse" "frog") yet I still get the same error.

What am I doing wrong? I'm using bash 5.1.4 on debian 11

The tutorials I'm referencing are:

https://opensource.com/article/18/5/you-dont-know-bash-intro-bash-arrays

https://tldp.org/LDP/Bash-Beginners-Guide/html/sect_10_02.html

https://www.freecodecamp.org/news/bash-array-how-to-declare-an-array-of-strings-in-a-bash-script/

Brad
  • 1
  • 1
  • Are you running the script by explicitly specifying another interpreter than `bash`, like `sh` for example? You should treat each separate shell as a separate language. You wouldn't run a Perl script with the `python3` interpreter... – Kusalananda Oct 02 '21 at 19:13
  • yes I was... this simple solution fixed it. thanks! – Brad Oct 02 '21 at 19:14
  • please post the answer so I can vote it resolved for you – Brad Oct 02 '21 at 19:14
  • also, quote your variables when you use them. `for i in "${!myArray[@]}"`, not `for i in ${!myArray[@]}` – cas Oct 03 '21 at 01:33

0 Answers0