How to pass the contents of a file using `cat` to `_values` (zsh completion)

五迷三道 提交于 2019-12-12 13:52:00

问题


Is it possible to pass the contents of a file using cat to _values (zsh completion)?

If I uncomment the line _values cat .test_tasks~ and comment _values below, it doesn't work, I get: _values:compvalues:10: invalid value definition: 1test[1.

#compdef test
#autoload

local curcontext="$curcontext" state line ret=1
local -a _configs

_arguments -C \
  '1: :->cmds' \
  '2:: :->args' && ret=0

_test_tasks() {
  # _values "test" $(cat .test_tasks~)

  _values "test" \
      "1test[1 test test]" \
      "2test[2 test test]"
}

case $state in
  cmds)
        _test_tasks
    ret=0
    ;;
  args)
        _test_tasks
    ret=0
    ;;
esac

return ret

.test_tasks~

1test[1 test test]
2test[2 test test]

It seems to be a problem with whitespaces. If I remove the whitespaces:

1test[1testtest]
2test[2testtest]

it works.

Any ideas?

Solution:

OLD_IFS=$IFS
IFS=$'\n'
_values $(< .cap_tasks~)
IFS=$OLD_IFS

Reference: Bash cat command space issue explained.


回答1:


You can use the mapfile module:

zmodload zsh/mapfile
_values ${(f)mapfile[.test_tasks~]}

The mapfile associative array provides access to the contents of external files. The parameter expansion flag (f) splits the resulting expansion on newlines, so that each line of the file will form a separate argument to _values.



来源:https://stackoverflow.com/questions/21356370/how-to-pass-the-contents-of-a-file-using-cat-to-values-zsh-completion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!