Fish中是否有可能以一种方式执行命令替换,我将命令定义为echo等命令的单个参数?在Bash中,它等同于:
$ echo "$(cat file.txt)"
lorem
ipsum
Run Code Online (Sandbox Code Playgroud)
Fish建议的方法不适用于多行(或间隔)输出:
$ echo (cat file.txt)
lorem ipsum
Run Code Online (Sandbox Code Playgroud)
如果我添加引号,它根本不执行命令替换:
$ echo "(cat file.txt)"
(cat file.txt)
Run Code Online (Sandbox Code Playgroud)
bash中的命令替换返回单个字符串.如果您对未加引号的字符串进行回显,则需要进行单词拆分和文件名扩展.
fish中的命令替换默认返回行列表.您可以通过重新注入换行符来打印结果:
$ printf "%s\n" (cat file.txt)
lorem
ipsum
Run Code Online (Sandbox Code Playgroud)
或者,您可以将IFS变量设置为空字符串,以便不会发生换行:
$ echo (cat file.txt)
lorem ipsum
$ begin; set -l IFS ""; echo (cat file.txt); end
lorem
ipsum
Run Code Online (Sandbox Code Playgroud)
要么
$ set contents (cat file.txt); echo $contents; echo (count $contents)
lorem ipsum
2
$ begin; set -l IFS ""; set contents (cat file.txt); end
$ echo $contents; echo (count $contents)
lorem
ipsum
1
Run Code Online (Sandbox Code Playgroud)
我正在新范围内本地重置IFS,以避免破坏shell中的当前值.
参考:https://fishshell.com/docs/current/index.html#expand-command-substitution