How should I export a shell variable in bash?

8,011

Solution 1

I believe that true Bourne shell (/bin/sh on many commercial Unix variants) does not support the assignment and export in a single statement. This is how I remember it from my days on Solaris.

I don't know if the new Solaris versions use bash by default now. Regardless, your latter case is more portable so I'd stick with that.

Solution 2

In Solaris, /bin/sh requires the two statements, while /bin/bash is fine with it on one statement. On linux, /bin/sh is usually a symlink to /bin/bash, so there isn't a difference.

If you are writing a script which may be sourced by another script, then always use the two statement format. If the script isn't or won't be sourced, just check the shebang line at the top of the script to see which shell your using. Many Solaris scripts use /bin/sh, and this is the default for many software packages. As such most admin prefer the more portable way of exporting a variable.

Solution 3

I am working on Solaris 2.6, circa 1998. This version only came with sh and csh originally. Using sh, I see that you need the two line version you mention in order to see the correct result from env. Using bash from sunfreeware.org, and it works fine with the one line version.

Solution 4

Any modern Bourne derived shell that I'm aware of supports the all-in-one form. I think older versions of the original Bourne shell may require the separate version.

Share:
8,011

Related videos on Youtube

brianegge
Author by

brianegge

Updated on September 17, 2022

Comments

  • brianegge
    brianegge almost 2 years

    I usually work in bash in Linux, and if I need to export a variable I might write:

    export LC_ALL=C
    

    However, I am doing more Solaris work these days, and Solaris Admin's I work with will always write:

    LC_ALL=C ; export LC_ALL
    

    Is there a reason to prefer the latter over the former?

    I guess that the former might not be recognised by some shells. Which ones?

    Thanks.

  • Phil Hollenback
    Phil Hollenback over 14 years
    Yup that's exactly it - this is neckbeard territory. If you are using a real bourne shell then you have to use two statements, otherwise with bash you can combine the two.
  • ScottZ
    ScottZ over 14 years
    Nowadays /bin/sh is typically a symlink to a dumbed down more strict shell called dash (This is definitely the case in all modern Debian distros). So like the first post states it is better to go with the more portable solution. However dash does seem to support the one line statement :)
  • peterh
    peterh over 7 years
    Extra info: As of Solaris 11 (2011 onwards) the combined export command is supported by default, so no longer something to consider.