Skip to content

Expressions inline with a slice are ignored or cause parse errors #2280

Open
@n4zukker

Description

@n4zukker

Describe the bug
The slice array operator does not work as expected when used after an expression.

  1. Since ["cat", "dog", "frog", "cow"][1] evaluates to "dog",
    I would expect ["cat", "dog", "frog", "cow"][1:] to evaluate to ["dog", "frog", "cow"].
    But it acts as .[1:] was written and returns the slice of the input.

  2. An error is returned in the case of the "without the first number" array slice.

yq should give an error in both cases or, better yet, support both. In the first case, it's a bug to accept the syntax and ignore the left hand side. In the second case, the error message is not intuitive.

Version of yq: 4.45.1
Operating system: ubuntu
Installed via: direct download from https://github.com/mikefarah/yq/releases/download/v4.45.1/yq_linux_amd64

Input Yaml
Concise yaml document(s) (as simple as possible to show the bug, please keep it to 10 lines or less)
data1.yml:

- 'entry 1'
- 'entry 2'
- 'entry 3'

Command
The command you ran:

./yq_linux_amd64  '["cat", "dog", "frog", "cow"][1:]' data1.yml

Actual behavior

- 'entry 2'
- 'entry 3'

Expected behavior

- dog
- frog
- cow

Command
The command you ran:

./yq_linux_amd64  '["cat", "dog", "frog", "cow"][1:2]' data1.yml

Actual behavior

- 'entry 2'

Expected behavior

- dog

Command
The command you ran:

yq '["cat", "dog", "frog", "cow"][:2]' data1.yml ;
yq '"expr" | ["cat", "dog", "frog", "cow"][:2]' data1.yml

Actual behavior

Error: '' expects 2 args but there is 1
Error: '|' expects 2 args but there is 1

Expected behavior

- cat
- dog

- cat
- dog

Additional context
.b[1:] acts similarly, as does $arr[1:].

Once you are aware of this bug, you can work around it by moving the expression to input and using a dot, .[n:m]. E.g. instead of
["cat", "dog", "frog", "cow"][1:] write
["cat", "dog", "frog", "cow"] | .[1:]
but until then it's a head scratcher for either of the cases.

Ref: Slice array man page: https://mikefarah.gitbook.io/yq/operators/slice-array

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions