Bashコンプリート関数のいくつかの共通変数の範囲とソース

Bashコンプリート関数のいくつかの共通変数の範囲とソース

cur、prev、分割、単語、cwordなどの変数があります。完成関数に使用できる値があるようです。どこで定義され割り当てられていますか?どこかに輸出されますか?これらの変数を完了時に同じ名前のローカル変数として宣言する必要がありますか?

ベストアンサー1

事前定義された関数_init_completion(宣言は次のようになります)を使用する場合これ)私の完成関数では、いくつかの変数をローカル変数として宣言する必要があります。

上記の声明を引用すると、次のようになります_init_completion

# Initialize completion and deal with various general things: do file
# and variable completion where appropriate, and adjust prev, words,
# and cword as if no redirections exist so that completions do not
# need to deal with them.  Before calling this function, make sure
# cur, prev, words, and cword are local, ditto split if you use -s.

wordsおそらく配列として使用されるので、ローカル配列として宣言する方が良いかもしれません。そのような他の関数を使用する場合は、他の変数を宣言する必要があるかもしれません。必要なものがあるかどうかを確認することをお勧めします。

Bashで変数の範囲をテストします。

local関数で使用する場合a

(
    x=1
    (
        unset -v x
        b() { echo $x; x=b; }
        a() { local x=a; b; echo $x; }
        a
        if [[ ${x+x} ]]; then
            echo $x
        else
            echo 'x is unset'
        fi
    )
    echo $x
)

出力は次のとおりです

a
b
x is unset
1

localしかし、関数で使用しない場合a

(
    x=1
    (
        unset -v x
        b() { echo $x; x=b; }
        a() { x=a; b; echo $x; }
        a
        if [[ ${x+x} ]]; then
            echo $x
        else
            echo 'x is unset'
        fi
    )
    echo $x
)

出力は次のとおりです

a
b
b
1

つまり、呼び出し側は値を使用できますa

おすすめ記事