-1

I was going through the shell script book, but in the array section, I got stuck. when I declare the array and run the script like:

sh hello.sh

it shows me the error, even in ZSH, is below:

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

when I run like this ./hello.sh, it's working like a charm.

This is the Script

#!/bin/bash
myarr=(on two three four five)
echo "${myarr[1]}"
exit 0

Note: why the sh isn't working, please. I'm a newbie in the shell!

Ericgit
  • 101

1 Answers1

2

The reason for this is Bourne Shell (sh) do not support array (not in this way you want to use). So do not use sh, stay with bash, ksh, zsh, etc.

You can find more info in this answer

The Bourne shell or the POSIX sh language specification don't support arrays. Or rather they have only one array: the positional parameters ($1, $2, $@, so one array per function as well).

And f run as sh hello.sh will be read by sh independently from shebang and current shell.

Romeo Ninov
  • 17,484
  • 1
    Thanks a lot! you solved my mind. – Ericgit Dec 22 '19 at 05:45
  • There are three things here I don't understand, and which may confuse those who see this later: (a) Why does a script called "hello.sh" report an error saying it came from "one.sh"? (b) When it shows the error "even in zsh", does that mean with zsh ./hello.txt (which should work), or with sh command but with the shebang now /bin/zsh? (c) The actual issue (not addressed) is that running a script with an explicit shell treats the intended shebang as a mere comment. – Paul_Pedant Dec 22 '19 at 17:17
  • @Paul_Pedant, the script can be named, renamed by OP on different ways so if its hello, one it does not matter. If run as sh script will be read by sh independently from shebang and current shell. – Romeo Ninov Dec 22 '19 at 17:21
  • I understood all that, but it shows that the posted output did not come from the posted script, and three different shells were involved, and that the role (or otherwise) of the shebang was ignored. – Paul_Pedant Dec 22 '19 at 17:29