3

I am creating a custom completion for my command ipadd which will automatically complete all the network devices for OS X. It has a parameter --device which allows you to specify the network devices on the system.

The command to list the network devices in OS X is

networksetup -listallnetworkservices

The output for it is;

An asterisk (*) denotes that a network service is disabled.
Ethernet
Wi-Fi

However the first line of the command isn't the network interface and I have modified that command about so that it only shows Ethernet and Wi-Fi

networksetup -listallnetworkservices | sed -n '2,$p'

The output for this is;

Ethernet
Wi-Fi

My question is how can I store that command and use it for auto completion for my ipadd command. I know that you can use the _files but that is for completing files within the system.

Thanks in advance :)

0
  1. Create a file named _ipadd and put the following in it:
    #compdef ipadd
    
    # The line above declares this function as providing completions to 
    # `ipadd`. In addition, it's important that the file name starts with 
    # an `_`, otherwise `compinit` won't autoload it.
    
    local output=$(networksetup -listallnetworkservices)
    
    # Split the output on newlines.
    local -a services=( ${(f)output} )
    
    # Offer the second to the last line as completions.
    _arguments "*:network service:( ${services[2,-1]} )"
    
  2. Make sure the folder that contains this file is in your $fpath. So, if we suppose it's located in ~/func, then you can do something like this in your .zshrc file:
    fpath+=( ~/func )
    
  3. Make sure you call compinit in your ~/.zshrc file after adding the dir to your $fpath. Otherwise, it will not be used for completions.
    autoload -Uz compinit && compinit
    

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.