4

これらのコマンドは、エクスポート時に読み取り専用の変数が残っていないことを示しているようです。

バッシュ バージョン 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 に答える