2

I have a custom script that requires one argument in the form of --host=hostname, and allows one optional argument -n, --dry-run.

I have created zsh completion, where the optional argument is being offered:

#compdef sync-data.sh

_sync-data.sh () {
  local -a args

  args+=(
    '(-n --dry-run)'{-n,--dry-run}'[show what would have been transferred]'
  )

  _arguments $args && return
}

_sync-data.sh "$@"

But how can I add the required --host=hostname, so that:

  1. it is completed as first argument
  2. the part after = is completed from my _hosts completions
  3. --dry-run is only offered for completion after the required option --host= is provided
  4. after --host=hostname is provided, and optionally --dry-run, not other completions are offered (ie, no local filenames).
1

1+2) Add something like the following as a parameter to _arguments:

    '--host=[specify host]:host:_hosts'

The part in square brackets is a description that can likely be improved.

  1. Make adding --dry-run to args conditional. (( CURRENT > 2 )) adds it from the second word on. (( $words[(I)--host*] )) checks for the presence of --host on the command-line. It depends what is appropriate.

  2. That should be the default situation.

You've go some superfluous elements in your function. There's no need to define a _sync-data.sh as the entire contents of the file and then call it. That's only useful when you have multiple functions defined from the one. autoloadable functions are already a function. Also, the && return is superfluous. Functions pass on the return status of the last command.

The whole code as per comment request:

#compdef sync-data.sh

local -a args

(( $words[(I)--host*] )) && args+=(
  '(-n --dry-run)'{-n,--dry-run}'[show what would have been transferred]'
)

_arguments $args \
  '--host=[specify host]:host:_hosts'
1
  • where exactly should I add the conditional? Could you please copy paste the whole code, including the optimizations you suggest (removing superfluous code) ? – 400 the Cat Feb 15 at 10:13

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.