2

A question on basics : While tuning environment variables for a program launched from a script, I ended up with somewhat strange behaviour with sh (which seems to be actually linked to bash) : variable setting seems to mess up with command-line parameters.

Could somebody explain why does this happen?

A simple script:

#! /bin/sh

# Messes with $1 ??
set ANT_OPTS=-Xmx512M
export ANT_OPTS

# Works
# export ANT_OPTS=-Xmx512M

echo "0 = $0"
echo "1 = $1"

When I run this with the upper alternative (set + export), the result is as following:

$ ./test.sh foo
0 = ./test.sh
1 = ANT_OPTS=-Xmx512M

But with lower alternative (export straight), the result is as I supposed:

$ ./test.sh foo
0 = ./test.sh
1 = foo

There is surely logical explanation, I just haven't figured it out yet. Somebody who does have idea?

br, Touko

Touko
  • 11,359
  • 16
  • 75
  • 105
  • 1
    "set" isn't part of Bourne Shell. That should be `ANT_OPTS=-Xmx512m\nexport ANT_OPTS` – Paul Tomblin May 26 '10 at 13:42
  • 2
    @Paul Tomblin: `set` is indeed a bash built-in (though you're of course right that it's not what you want to use here). http://www.gnu.org/software/bash/manual/bashref.html#The-Set-Builtin – Cascabel May 26 '10 at 13:43
  • 7
    Maybe I'm old fashioned, but if your shebang is `#!/bin/sh` then you shouldn't be using things that are bash extensions, it should be straight Bourne Shell. If you want to use bash extensions, then you should state so up front with `#!/bin/bash` – Paul Tomblin May 26 '10 at 13:47

2 Answers2

5

You should just use ANT_OPTS=-Xmx512M instead of set ANT_OPTS=-Xmx512M.

UPDATE: See here for discussion of set, and the manual.

Hank Gay
  • 70,339
  • 36
  • 160
  • 222
  • OK, that also solves the behavior that I didn't expect. Thanks! – Touko May 26 '10 at 13:48
  • 1. As @Paul Tomblin mentions in a comment, if you're using `#!/bin/sh` you should restrict yourself to just Bourne Shell, but `bash` is what you're going to get from `/bin/sh` on pretty much every single Linux distro, so if you get bugs it might be because you used a `bash`-ism by accident. 2. If you're coming to `bash` from `csh` or similar, you should probably find a good book and dig in; it seems like `bash` was *designed* to confuse people who already know `csh` (and vice versa). – Hank Gay May 26 '10 at 14:00
2

"set" isn't part of setting variables in Bourne Shell. That should be

ANT_OPTS=-Xmx512m
export ANT_OPTS 
Paul Tomblin
  • 179,021
  • 58
  • 319
  • 408