You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Cannot save multi-line output in a variable (support $() command substitution syntax) #159
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.
Reacted by Tobias Bradtke, Phil Cohen, Ivan Kozik, Moritz Kneilmann, Viktor Stanchev, Adriaan, René Schwaiger, c02y, Ivana Zemanovicova, Alexey Alekhin and 78 more
Reacted by Braham Snyder, Ivana Zemanovicova, mikesm, Dmitri, Patrick Seidensal, Gianluca Recchia, Markus Padourek, Devin Buhl, jos128, Walter Johnson and 6 more
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
Reacted by Ron Wolf, lordlycastle, Aaron Nel and Zdeněk Biberle
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.
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.
Reacted by Ron Wolf, Mikel Ward and Zdeněk Biberle
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.
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.
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?
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)
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.
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.
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 ().
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 $():
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
Alternatively, make substitution output be unquoted and allow it inside double quotes. This is a pretty big semantic change.
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.
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.)
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.
Reacted by avollmerhaus, Pysis, Patrick C., Anton Dyudin, Chris, Evan Benn, Mathieu PATUREL, David Kowis, Martin Kopischke, Ron Wolf and 15 more
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:
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:
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.
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. 🙏
Reacted by Avindra Goolcharan, Marcin Zajączkowski, waynema02, Jonathan Watt, Jose, Saeid Saati and Manuel
Reacted by Jason Nader, Saeid Saati, Manuel and Shannon Matthews
Reacted by Pablo Aguiar, Lily Ballard, waynema02, Jonathan Watt, Saeid Saati and Manuel
Reacted by Aurelio Jargas, blt-r, MidAutumnMoon, waynema02, Jonathan Watt, Oli Evans, Curstantine, Tim Vergenz, Scott Santucci, Mike Arvela and 5 more
Reacted by David Adam, Branch Vincent, Ilan Cosman, Pablo Aguiar, Grégoire Geis, Tim Steenvoorden, blt-r, waynema02, Jonathan Watt, Saeid Saati and 2 more
Activity
lilyball commentedon Jun 20, 2012
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
lilyball commentedon Jun 20, 2012
As a separate idea, if there was some flag to
echothat 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.lilyball commentedon Jun 20, 2012
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, andtest -nwith no subsequent arguments actually returns true.maxfl commentedon Jun 20, 2012
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.
lilyball commentedon Jun 20, 2012
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.maxfl commentedon Jun 20, 2012
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?
lilyball commentedon Jun 20, 2012
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)maxfl commentedon Jun 20, 2012
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.
ridiculousfish commentedon Oct 9, 2012
This outputs 1:
This outputs 3:
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.
maxfl commentedon Oct 9, 2012
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.
ridiculousfish commentedon Oct 9, 2012
My suggestion was actually in the other direction: treat newlines like spaces (so they do not split). So
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.maxfl commentedon Oct 10, 2012
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 ().
Soares commentedon Oct 17, 2012
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,
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:
That I get. Quotes prevent splitting. Cool.
Ok and it looks like subcommands are automatically considered quoted...
And newlines don't count as whitespace when you're splitting things, that's cool I guess
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: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
$():count "one\ntwo\nthree"is1thencount (echo one\ntwo\nthree)should be1dicecommand which splits output-in-lines into quoted-args-separated-by-spaces. This is analogous to how we havepsubinstead of process substitution: fish should prefer new commands to new syntax.seta 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
countor()usage.)echoa 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:
Which is a big change, but is at least consistent.
Many of these are more work-arounds than solutions. And even if we fix
setandechoby adding more flags we still have thecountelephant in the room, which can't take any flags of any sort: if we add flags tosetthat tell it how to split arrays then it seems pretty silly thatcountcan 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 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.
ridiculousfish commentedon Oct 17, 2012
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:
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:
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.
115 remaining items
Support "$()" command substitution without line splitting
Support "$()" command substitution without line splitting
Support "$(cmd)" command substitution without line splitting
Support "$(cmd)" command substitution without line splitting
Support "$(cmd)" command substitution without line splitting
Support "$(cmd)" command substitution without line splitting
Support "$(cmd)" command substitution without line splitting
Support "$(cmd)" command substitution without line splitting
Support "$(cmd)" command substitution without line splitting
pirate commentedon Jul 13, 2021
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
Example Usage
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 😁 👏 :
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. 🙏
Support "$(cmd)" command substitution without line splitting