4

These commands seem to show that a readonly variable does not remain so when exported:

Bash version 4 or higher

f() {

    # A local variable will be visible within the function in which it is declared
    local a=1

    # Declare acts as a synonym (?) to local here, as I do not specify -g (global)
    declare b=2

    # This is a regular global variable, it won't be in new shells because not exported
    declare -g c=3

    # You may find this puzzling: _not_ exported because not marked also global
    declare -x d=4

    # This should be read-only but it does not even get exported
    declare -xr e=5

    # This will be both global and exported, as expected. Phew :)
    declare -gx f=6

    # Same as f, global and exported
    export g=7

    # Now interestingly: this should be exported as read-only, but...
    declare -grx h=8

    # What does the function scope look like?
    printf '%-10s %d%d%d%d%d%d%d%d\n' "local" "$a" "$b" "$c" "$d" "$e" "$f" "$g" "$h"
}

f

# What does the global scope look like?
printf '%-10s %d%d%d%d%d%d%d%d\n' "global" "$a" "$b" "$c" "$d" "$e" "$f" "$g" "$h"

# What does the scope of a new shell look like?
bash -c 'printf "%-10s %d%d%d%d%d%d%d%d\n" "new shell" "$a" "$b" "$c" "$d" "$e" "$f" "$g" "$h"; h=42; echo "$h"'
# Read-only attribute has disappeared after exportation

output:

local      12345678
global     00300678
new shell  00000678
42

Is there any way to export variable attributes? Which ones export well?

Robottinosino
  • 10,384
  • 17
  • 59
  • 97
  • Could you explain what you're trying to achieve by way of read-only exported variables? – devnull Apr 08 '13 at 06:00
  • Also keep in mind -g wasn't added until Bash 4.2 (per [this](http://stackoverflow.com/questions/10806357/associative-arrays-are-local-by-default)). – Chris R. Donnelly Apr 28 '16 at 17:49

1 Answers1

0

I'd doubt that it's possible to have read-only variables that can be exported.

In order to have read-only global variables, try using the readonly built-in, e.g.

readonly c=3
devnull
  • 118,548
  • 33
  • 236
  • 227