Niccolo M. Niccolo M. - 15 days ago 9
Bash Question

Is it portable to do "export VAR=value" in shell scripts?

I see a lot of snippets that do:

SOME_LONG_VARIABLE_NAME=whatever_value
export SOME_LONG_VARIABLE_NAME


And I was wondering why people don't just do:

export SOME_LONG_VARIABLE_NAME=whatever_value


My questions:


  1. Is a POSIX-conforming shell required to support the
    export VAR=value
    syntax? I.e., is it portable?

  2. If so, why isn't this shorter syntax prevalent?


Answer

"Is it portable" is not quite the same question as "is it POSIX". export var=value is specified by POSIX, but it is not portable if you target the wider group of all (current and legacy) Bourne-like shells.

I don't know if there are any systems currently being sold by a vendor that don't allow this syntax. But again, "systems currently being sold" and "systems currently running" are different questions. We'd need some actual users of AIX, HP-UX, Solaris, etc. to stop by and tell us...

You may find a script using the two-step "assign then export" for any of these reasons:

  1. The script was written a long time ago and has been in maintenance mode since then. Combining the statements would be a purely cosmetic change, which is undesirable.
  2. The script is actually intended to run on some legacy system with a non-POSIX /bin/sh
  3. The author learned shell programming a long time ago and just does things out of habit, knowing that the old ways (when not contradicted by POSIX) are at least as portable as POSIX. This type of person may also be seen using expr for arithmetic, and the mystical construction ${1+"$@"} may appear.
  4. (the worst case) The author copied bits and pieces of other scripts without understanding them, and this piece came from a script in one of the previous categories.
Comments