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?

jarno
  • 620

1 Answers1

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.

jarno
  • 620