bashdeclare

`declare -x` vs `export` inside a function


I always considered declare equivalent to local when used within a function and declare -x equivalent to export.

f() {
        declare -x k=1
}

f

echo $k

The above was expected to show 1, but displays nothing.

Meanwhile export k=1 (as well as declare -gx k=1) work as expected. Does this have any logical explanation, is it otherwise documented anywhere?


Solution

  • Let's look at declare's documentation, which has the relevant parts quoted below:

    Options which set attributes:

    -x - To make names export

    When used in a function, 'declare' makes NAMEs local, as with the `local' command. The '-g' option suppresses this behavior.

    Nothing states or implies that -x implies -g.


    Consequently, declare, as you say, is equivalent to local when used in a function without the -g argument. Similarly, declare -x is identical to local -x, except insofar as declare works when not used inside a function, whereas using local outside function scope is an error.