1
export CLASSPATH=$(JARS=(./lib/*.jar); IFS=:; echo "${JARS[*]}")

If I put this line in a bash_script.sh and do

chmod +x bash_script.sh

and then run

./bash_script.sh

it gives the error.

Syntax error: "(" unexpected (expecting ")")

How ever I am able to run this thing directly from the prompt and get the expected result. as

$ export CLASSPATH=$(JARS=(./lib/*.jar); IFS=:; echo "${JARS[*]}")

I was wondering what is the reason for this strange behaviour.

adarshr
  • 61,315
  • 23
  • 138
  • 167
liv2hak
  • 14,472
  • 53
  • 157
  • 270
  • 1
    Does your script explicitly have a `#!/bin/bash` at the top? And what is your interactive command shell? – splungebob Aug 12 '13 at 21:32
  • 1
    It works for me w/o errors either from command prompt or executing as script (albeit with no results). – splungebob Aug 12 '13 at 21:38
  • adding #!/bin/bash at the top does make it work for me – liv2hak Aug 12 '13 at 21:39
  • Since it helped you, I added it as an answer. – splungebob Aug 12 '13 at 21:41
  • Even if you put in a shebang line some people will still try to call your script with `sh bash_script.sh` so I suggest putting in a `set +o posix` in as well, to disable posix compliancy explicitely. Best way though is avoid the bashism and do a combination of `find` and `paste` to build the classpath. – David Ongaro Jun 26 '14 at 04:48

2 Answers2

1

Add #!/bin/bash as the first line to force it to be run in the bash shell.

splungebob
  • 5,357
  • 2
  • 22
  • 45
1

Make sure you have #!/bin/bash at the top of your shell script. Array syntax VAR=(...) is a bash-ism. It won't work in plain sh (#!/bin/sh).

By the way, that looks like a line from my answer here. If so, I encourage you to use my updated solution rather than this.

There's no need to manually build the classpath list. Java supports a convenient wildcard syntax for directories containing jar files.

java -cp "$LIB/*"

(read more)

Community
  • 1
  • 1
John Kugelman
  • 349,597
  • 67
  • 533
  • 578