Skip to content

Cannot save multi-line output in a variable (support $() command substitution syntax) #159

Closed

Description

@lilyball

There seems to be no way to capture multi-line output in a shell variable. Any attempt to do so splits each line into a separate array element. In bash I'd simply put double-quotes around my $() invocation, but in fish you cannot quote a command substitution. This is rather unfortunate because it means I cannot capture multi-line output in a variable and send it back to a separate command without really weird contrivances, such as replacing all newlines with NUL when saving and reverting the process when emitting.

Activity

  1. lilyball commented on Jun 20, 2012

    @lilyball
    ContributorAuthor

    And for the record, doing such a replacement makes it impossible to look at the status of the original command* (e.g. in issue #158), because Fish provides no replacement for bash's PIPESTATUS.

    *without really stupid things like piping the output to a file temporarily

  2. lilyball commented on Jun 20, 2012

    @lilyball
    ContributorAuthor

    As a separate idea, if there was some flag to echo that made it emit each argument on a separate line instead of space-separation, that would at least provide a workaround. And yes, this is something that can be shellscripted. But it really shouldn't be necessary.

  3. lilyball commented on Jun 20, 2012

    @lilyball
    ContributorAuthor

    The lack of a way to quote a command substitution has just reared its head in another location: the inability to use command substitution with test -n. If the command substitution results in no output, it also results in no arguments at all, and test -n with no subsequent arguments actually returns true.

  4. maxfl commented on Jun 20, 2012

    @maxfl
    Contributor

    For me it looks quite natural: no output - no arguments. One empty line of output - one empty argument.
    What is strange for me is why 'test -n' returns 0 at all? Naively I would suppose it to return 1.
    I would suggest to change the returning value for this case, but the system 'test' and the bash internal 'test' also return 0 in this case.

    Concerning the multi-line output I completely agree with you. It would be very nice to have possibility to do command substitution inside double quotes, something like "$()", because substituting "()" is dangerous.

  5. lilyball commented on Jun 20, 2012

    @lilyball
    ContributorAuthor

    As an alternative to $() (which, btw, I still want just so I can more easily combine command substitution with surrounding variables, etc), it might be nice to just have a trivial way of taking a multi-element variable and creating one argument with all elements joined by a newline. This would effectively reverse the process of storing a command substitution into a variable, with the one exception that this will force a trailing newline when the command substitution may not have had one. Right now I can write (for elem in $var; echo $elem; end), but that's rather awkward to do everywhere.

  6. maxfl commented on Jun 20, 2012

    @maxfl
    Contributor

    Shorter ways to do the same:
    (printf '%s\n' $var)
    or
    (echo $var\n)?
    But fish again splits the substitution into arguments by newlines. How do you use it?

  7. lilyball commented on Jun 20, 2012

    @lilyball
    ContributorAuthor

    I assume you mean printf, and that would work but it has to spawn a separate process which is slow.

    As for (echo $var\n), that's going to put a space after every newline, which is wrong, as well as include two newlines at the end.

    The use of this is for piping to another process. Obviously storing it back in a variable would just split it again, but I can say (for line in $var; echo $line; end | grep foo)

  8. maxfl commented on Jun 20, 2012

    @maxfl
    Contributor

    You are right.
    echo you can use when you do not care about extraspace (like in grep example). And printf when you do not care about preformance.

  9. ridiculousfish commented on Oct 9, 2012

    @ridiculousfish
    Member

    This outputs 1:

    count (printf "%s %s %s" first second third)
    

    This outputs 3:

    count (printf "%s\n%s\n%s" first second third)
    

    I don't understand why newlines from a substitution result in arrays, while spaces from a substitution do not. I wonder how bad it would be to treat whitespace uniformly here.

  10. maxfl commented on Oct 9, 2012

    @maxfl
    Contributor

    I think that it's perfectly consistent behaviour (considering that fish distinguishes whitespaces). From my experience automatic expanding space-separated strings to array makes it difficult to cope with space containing strings and lead to rather extensive subquoting.

    From the other hand: additional splitting can be implemented by additional command. But if fish will split all whitespaces it will be difficult to glue them back if needed.

  11. ridiculousfish commented on Oct 9, 2012

    @ridiculousfish
    Member

    My suggestion was actually in the other direction: treat newlines like spaces (so they do not split). So

    count (printf "%s\n%s\n%s" first second third)
    

    would output 1. On the other hand, then we would need some way to split a string.

    I also think kballard's suggestion of quoted substitutions via e.g. "$(echo hello)" is very good and would address this neatly.

  12. maxfl commented on Oct 10, 2012

    @maxfl
    Contributor

    I completely agree about "$(echo hello)".
    I also sometimes think, that replacing () by $() in normal mode is a good
    way, because in this case there will be no need to escape ().

  13. Soares commented on Oct 17, 2012

    @Soares
    Contributor

    Personally I'm very -1 to $() syntax.

    One of the things that drew me to fish was that it simplifies all of the crazy different ways to do things that bash/zsh/etc have.

    See the design doc, the law of orthogonality. To quote,

    The shell language should have a small set of orthogonal features. Any situation where two features are related but not identical, one of them should be removed
    ...

    • The many Posix quoting styles are silly, especially $''.

    I think it would be a serious degradation of fish's principles to add $() syntax.

    From what I understand, adding a third quoting syntax ("" vs '' and unquoted) was a large and difficult decision. If we're going to do a change like this we should at least strongly consider all alternatives first.

    Understanding the whitespace rules right now is a big pain point. Currently:

    > count 'one two three'
    1
    > count one two three
    3
    

    That I get. Quotes prevent splitting. Cool.

    > count (echo one two three)
    1
    

    Ok and it looks like subcommands are automatically considered quoted...

    > count one\ntwo\nthree
    1
    

    And newlines don't count as whitespace when you're splitting things, that's cool I guess

    > count (echo one\ntwo\nthree)
    3
    

    Wait, what?! Something's seriously smelly here. If (echo one two three) acts like 'one two three' then (echo one\ntwo\nthree) should act like 'one\ntwo\nthree'.

    And, of course, the big scripting problem is that the data isn't preserved by set:

    > set foo (echo one\ntwo)
    > echo $foo
    one two
    

    We had newlines and now we have spaces.

    I understand why it all works like this but it definitely doesn't seem very fish-like. User focus is violated here, orthogonality certainly isn't helped. I'm not sure what the answer is, but any or all of these are options I like better than $():

    1. Substitution output should be treated exactly like a quoted string. If count "one\ntwo\nthree" is 1 then count (echo one\ntwo\nthree) should be 1
    2. Alternatively, make substitution output be unquoted and allow it inside double quotes. This is a pretty big semantic change.
    3. Don't split output on newlines by default. Add a dice command which splits output-in-lines into quoted-args-separated-by-spaces. This is analogous to how we have psub instead of process substitution: fish should prefer new commands to new syntax.
    4. Give set a new flag which tell it how to dice variables.
      (Pros: you could split things on colons if that's your thing. Con: doesn't help count or () usage.)
    5. Give echo a new flag which tells it how to separate args (fixes the symptoms not the problem.)

    Concerning option 2, it would mean that unquoted command substitution would act like this:

    > count one two three
    3
    > count "one two three"
    1
    > count (echo one two three)
    3
    > count "(echo one two three)"
    1
    

    Which is a big change, but is at least consistent.

    Many of these are more work-arounds than solutions. And even if we fix set and echo by adding more flags we still have the count elephant in the room, which can't take any flags of any sort: if we add flags to set that tell it how to split arrays then it seems pretty silly that count can never have the same functionality.

    I'm most in favor of 1. or 2. above, but either way I'm against adding $() syntax. One more design doc quote:

    Most tradeoffs between power and ease of use can be avoided with careful design.

    Most of my ideas above are still half-baked, but I think more carefully designing the text-splitting rules is a far superior option to adding more syntax and flags on top of the existing ones in an attempt to patch all the holes. That sort of activity is what got bash where it is today.

  14. ridiculousfish commented on Oct 17, 2012

    @ridiculousfish
    Member

    Thank you for the thoughtful comments Soares.

    I think there might be a point of confusion. The $() proposal is to add a way to do command substitutions within double quotes. It need not work outside of them:

    > count (echo 1\n2\n3)
    3
    > count "$(echo 1\n2\n3\n)"
    1
    > count $(echo 1\n2\n3\n)
    syntax error
    

    In that way I think it's similar to your suggestion 2 above. The dollar sign has the advantages of not requiring escaping parens within double quotes (which would be irritating), and because it doesn't conflict with any existing valid syntax.

    This was an element of kballard's "Fish Scripting Wishlist" from June 21. To quote Kevin:

    1. Fish needs a way to do command substitution within a double-quoted string. The simplest solution is probably to support $() within double-quotes. The reasoning is twofold: first, a command substitution that evaluates to no output ends up being stripped entirely from the argument list of its surrounding command. This has extremely bad implications when using it with, e.g. test -n (some command). Second, this would allow for storing the output with its newlines in a variable, instead of having the output be split into multiple elements. And as a bonus it would make it a lot easier to combine command substitution output with other text in the same argument, e.g. "$somevar"(some command)"$anothervar".

    So "$()" would solve several problems, which is why it's interesting.

    I think we'd also like to avoid splitting on newlines as you suggest in 3 above. The main blocker there is the sheer quantity of work required to vet all existing fish code, and in adding the new 'dice' command.

  15. 115 remaining items

  16. added 2 commits that reference this issue on Jun 15, 2021
    f32b9b0
    cbcee44
  17. added a commit that references this issue on Jun 23, 2021
    7f5b3ff
  18. added a commit that references this issue on Jul 3, 2021
    71f5a61
  19. added 4 commits that reference this issue on Jul 10, 2021
    73a19b6
    5020012
    23541b7
    bfc6784
  20. added a commit that references this issue on Jul 13, 2021
    ec3d3a4
  21. pirate commented on Jul 13, 2021

    @pirate

    The new support for $(cmd)/"$(cmd)" added in #8059 is amazing, thank you so much @krobelus for working on this, and @ridiculousfish for approving it!! 🎉 👏 👏 👏 ✨


    For anyone curious on how the new "$(cmd)" support works, the documentation for it is added here: bf5d2d1 (#8059).

    Usage Documentation

    A command substitution can have a dollar sign before the opening parenthesis like outercommand $(innercommand). This variant is also allowed inside double quotes. When using double quotes, the command output is not split up by lines.

    A command like echo (cmd | string collect) is mostly equivalent to a quoted command substitution (echo "$(cmd)"). The main difference is that the former evaluates to zero or one elements whereas the quoted command substitution always evaluates to one element due to string interpolation.

    fish's command substitution syntax has been extended: $(cmd) now has the same meaning as (cmd) but it can be used inside double quotes, to prevent line splitting of the results. (:issue:159).

    Example Usage

    $ echo "zero $(echo one\ntwo\nthree) four"
        zero one
        two
        three four

    And just to close things out I want to quote my favorite comment #8059 (comment) from the PR by @ridiculousfish themself regarding @krobelus's implementation 😁 👏 :

    ridiculousfish: @krobelus I stand in awe. My approach was to teach fish about cmdsubs in quotes everywhere, which meant a lot of complexity and recursion. Your trick of making cmdsubs "temporarily close" quotes is so brilliantly simple, I would not have believed it possible! I learned from it today.


    P.S. @krobelus do you have a Paypal/Patreon/Github Sponsors/GitTip/etc.? I'd love to send you a tip as a thank you for working on this feature and knocking it out of the park, your work here closes one of the longest outstanding issues I've been waiting for on the fish project, and I'd love to show my thanks. 🙏

  22. modified the milestones: next-major, fish 3.4.0 on Jul 14, 2021
  23. added a commit that references this issue on Jul 28, 2021
    ab7e6a2
  24. locked as resolved and limited conversation to collaborators on Jun 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions