2

I'm already scratching my head for a while because of this:

> cat file
line1
line2
> set tst (cat file)
> echo "$tst" 
line1 line2
> set tst "(cat file)"
> echo "$tst"
(cat file)

In bash I can get it done like so:

$ cat file
line1
line2
$ tst=$(cat file)
$ echo "$tst"
line1
line2

2 Answers 2

4

By default, fish splits command substitutions ((command)) on newlines. To override that behavior, you can use the special string subcommands like string split (which allows you to define what to split on), string split0 (which splits on NUL bytes) and string collect (which doesn't split at all[0]).

So the answer is:

set tst (cat file | string collect)
echo $tst

[0]: Note that NUL bytes can't be passed to commands because unix passes the arguments as NUL-terminated strings, so there is no way for the command to know that the argument goes on, so string collect effectively just captures the command output up to the first NUL, giving you at most one entry, while string split0 might result in multiple arguments.

0
1

fish saves the result of a command substitution as a list of lines (except if string collect is used). So you can do

> set tst (cat file)
> printf '%s\n' $tst
line1
line2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.