如何保留存储在 var 中的 Fish shell 命令替换输出的格式?

Nar*_*asK 2 shell fish

由于这个原因,我已经挠头一段时间了:

> cat file
line1
line2
> set tst (cat file)
> echo "$tst" 
line1 line2
> set tst "(cat file)"
> echo "$tst"
(cat file)
Run Code Online (Sandbox Code Playgroud)

我可以像bash这样完成它:

$ cat file
line1
line2
$ tst=$(cat file)
$ echo "$tst"
line1
line2
Run Code Online (Sandbox Code Playgroud)

fah*_*aho 5

(command)默认情况下,fish在换行符上分割命令替换 ( )。要覆盖该行为,您可以使用特殊的字符串子命令,例如string split(它允许您定义要分割的内容)、string split0(它在 NUL 字节上分割)和string collect(它根本不分割[0])。

所以答案是:

set tst (cat file | string collect)
echo $tst
Run Code Online (Sandbox Code Playgroud)

[0]:请注意,NUL 字节不能传递给命令,因为 unix 将参数作为以 NUL 结尾的字符串传递,因此命令无法知道参数继续,因此string collect实际上只是捕获命令输出到第一个 NUL,最多给您一个条目,而string split0可能会导致多个参数。