1

There are variables like cur, prev, split, words and cword. They seem to have value I can use in my completion functions. Where are they defined and assigned? Are they exported somewhere? Should I declare those variables as local with same name in my completions?

0

If you use the pre-defined function _init_completion (whose declaration can be found like this) in my completion function, you should declare certain variables as local.

Quote from above of the declaration of _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.

Maybe it is best to declare words as local array because it is used as an array. If you use other such functions you may have to declare some other variables; it is better to check the code for what is needed, I think.

Test for variable scope in Bash:

If I use local in function 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
)

output is

a
b
x is unset
1

but if I do not use local in function 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
)

output is

a
b
b
1

i.e. the value is available for the caller of a.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.