Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 931
Pablo Cantero Avatar asked Jan 01 '26 03:01

Pablo Cantero


1 Answers

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.

like image 50
chepner Avatar answered Jan 05 '26 05:01

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!