1

`Given the following completion:

$ cat _anssh
#compdef anssh

_anssh () {
    _arguments '-i[inventory file]:filename:->files'
    case "$state" in
        files)
            _anssh_inventories_show
            ;;
        *)
            _anssh_hosts_show
            ;;
    esac
}

_anssh_inventories_show () {
    local -a inventories
    inventories=("${(@f)$(find hosts -maxdepth 1 -type f -printf 'hosts/%f\n')}")
    _multi_parts / inventories
}

_anssh_hosts_show () {
    local inv=$(echo $@ | sed 's/.*\-i\s*//g' | awk '{print $1}')
    local invflag=""
    if [ "$inv" != "" ]; then
        invflag="--inventory $inv"
    fi
    local hosts=("${(s/ /)$(anssh $invflag -l)}")
    _values 'hosts' $hosts
}

The part that does not work is that _anssh_host_show should return different values depending on how -i is defined (if it is defined). I try to extract the value of -i from $@ (which I expect to be the full command entered so far), but $@ is empty in context of the completion. How do I get that string instead?

0

This does the trick:

#compdef anssh

local -a command

_anssh () {
    command="$words"
    _arguments '-i[inventory file]:filename:->files'
    case "$state" in
        files)
            _anssh_inventories_show
            ;;
        *)
            _anssh_hosts_show
            ;;
    esac
}

_anssh_inventories_show () {
    local -a inventories
    inventories=("${(@f)$(find hosts -maxdepth 1 -type f -printf 'hosts/%f\n')}")
    _multi_parts / inventories
}

_anssh_hosts_show () {
    local inv=$(echo $command | grep ' -i' | sed 's/.*\-i\s*//g' | awk '{print $1}')
    local invflag=""
    if [ "$inv" != "" ]; then
        invflag="-i $inv"
    fi
    local hosts=("${(s/ /)$(anssh $invflag -l)}")
    _values 'hosts' $hosts
}

_anssh

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.