Bash导出属性

时间:2013-04-07 21:11:36

标签: bash

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

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

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

1 个答案:

答案 0 :(得分:0)

我怀疑可以导出只读变量。

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

readonly c=3