64

I have two (Debian) Linux servers. I am creating a shell script.

On the first one I create an array thus:

#!/bin/bash
target_array=(
    "/home/user/direct/filename -p123 -r"
)

That works fine. But when I run this on the other server I get:

Syntax error: "(" unexpected

As far as I can tell both servers are the same. Can anyone shed some light on why this doesn't work?

If I type it into the terminal directly it is fine??


It would appear that when I run it as

sh scriptname.sh

I get the error, but if I run it as

./scriptname.sh

it seems to be ok. What's the difference?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
IGGt
  • 2,137
  • 8
  • 28
  • 43
  • Did you copy-pasted the script between the two server? try `cat -v – LilloX Jan 07 '16 at 14:50

3 Answers3

106

When you use ./scriptname.sh it executes with /bin/bash as in the first line with #!. But when you use sh scriptname.sh it executes sh, not bash.

The sh shell has no syntax to create arrays, but Bash has the syntax you used.

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Konstantin Morenko
  • 1,438
  • 1
  • 9
  • 8
  • 3
    The sh language has no arrays (`a[index]=x` or `a=(x y)`). Some sh interpreters support arrays, only ksh88 (not ported to Linux AFAIK) and some older pdksh variants would support `a[index]=value` and not `a=(x y)`. On Debian, `sh` is usually `dash` which has no array support (`a[index]=x` won't work). – Stéphane Chazelas Jan 07 '16 at 15:38
1

Running ./scriptname.sh will result in reading the first line of the file and see that it needs to run ´/bin/bash´ and pass the rest of the script to the interpreter, while executing sh scriptname.sh will pass the file to the user's standard shell (e.g. Ash) and be the case that that other interpreter does not support arrays as Bash does.

dave_alcarin
  • 664
  • 1
  • 4
  • 14
  • 1
    `sh` is not necessarily the "user's standard shell" it's often its own executable (or symlink) and `sh` will be invoked to process the script. That will be true if even if the default login shell for that user is `bash` – Eric Renouf Jan 07 '16 at 15:26
  • That was the part in which I was not entirely sure at the moment. Thanks for the clarification! – dave_alcarin Jan 08 '16 at 08:44
0

With sh scriptname.sh, you are running it with sh, not necessarily with bash. Try comparing sh --version on both machines. And/or with dpkg -S $(which sh).

joepd
  • 2,357
  • 20
  • 19