4

这些命令似乎表明在导出时不会保留只读

Bash 版本 4 或更高版本

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

输出:

local      12345678
global     00300678
new shell  00000678
42

有没有办法导出变量属性?哪些出口好?

4

1 回答 1

0

我怀疑是否有可以导出的只读变量。

为了拥有只读的全局变量,请尝试使用readonly内置的,例如

readonly c=3
于 2013-04-08T06:00:22.190 回答