Ubuntu – For loop with Alphabet


This works perfectly on OSX

chars=( {a..z} )
for ((i=0; i<n; i++))
  echo "${chars[i]}"

But when I run it on Ubuntu, I get the following error.

ForLoopAlphabetTest.sh: 2: ForLoopAlphabetTest.sh: Syntax error: "(" unexpected

I can't seem to solve the issue. Any suggestions?

Best Answer

Presumably, you are running the script as:

sh ForLoopAlphabetTest.sh

In Ubuntu, sh is symlinked to dash; as dash has no concept of arrays, you are getting the syntax error for (.

The script works perfectly on bash, so it would be fine if you were running it as bash's argument:

bash ForLoopAlphabetTest.sh

Now, you have the bash shebang on the script, so you could make the script executable (chmod u+x ForLoopAlphabetTest.sh), and run it as:


or from the script's directory:


Also note that, your script contains brace expansion {a..z}, and C-style for construct: for (( ... )) which are also not supported by dash; so if your goal is portability, you should look at POSIX sh syntaxes only.