无法理解鱼shell命令替换 [英] Cannot understand command substitution in Fish shell
问题描述
在SH:
~$ `echo ls`
bin/ Desktop/
但在鱼:
fish: Illegal command name "(echo ls)"
~% (echo ls)
(注意,出现在命令行上述错误信息。)
(Note that the error message appears above the command line.)
~% echo (echo ls)
ls
~% eval (echo ls)
bin/ Desktop/
fish: Illegal command name "(echo ls)"
exec (echo ls)
^
~% exec (echo ls)
似乎命令替换只能作为命令参数,而不是一个命令本身?为什么呢?
It seems that command substitution only works as parameters of a command, not as a command itself? Why?
那么,帮助文档也说
如果一个参数包含了一组括号,按括号括起来的文本将作为PTED命令列表间$ P $。
If a parameter contains a set of parenthesis, the text enclosed by the parenthesis will be interpreted as a list of commands.
但尽管如此,为什么?
推荐答案
这是因为命令替换属于参数扩展和不允许作为命令。
How
This because command substitutions belong to parameter expansions and are not allowed as commands.
一个类似的例子:
在SH:
tmpls=ls
$tmpls
但在鱼:
% set cmd ls; $cmd
fish: Variables may not be used as commands.
...
为什么
总之,这是很好的可验证
Why
In short, it's good for verifiability
这文章解释细节:
由于它允许使用变量作为常规壳命令,就不可能可靠地检查一个脚本的语法。例如,该片段的bash / zsh中code可能会或可能不会是合法的,这取决于你的运气了。你觉得幸运吗?
Since it is allowed to use variables as commands in regular shells, it is impossible to reliably check the syntax of a script. For example, this snippet of bash/zsh code may or may not be legal, depending on your luck. Do you feel lucky?
if true; then if [ $RANDOM -lt 1024 ]; then END=fi; else END=true; fi; $END
这两个bash和zsh的尝试,以确定是否在用户presses回车键,但由于这样的问题,他们有时会失败当前缓冲区的命令完成。更糟的是,这件作品完全合法code是由bash的拒绝:
Both bash and zsh try to determine if the command in the current buffer is finished when the user presses the return key, but because of issues like this, they will sometimes fail. Even worse, this piece of perfectly legal code is rejected by bash:
FI=fi; foo() { if true; then true; $FI; }
鱼避免了这样的问题,因为变量不允许作为命令。任何你可以用的命令可以在任一使用的eval命令更清洁的方式来完成的变量或使用功能做的。
Fish avoids this kind of problem, since variables are not allowed as commands. Anything you can do with variables as commands can be done in a much cleaner way using either the eval command or by using functions.
有关的同样的理由,命令替换不允许作为命令
For the same reason, command substitutions are not allowed as commands.
(注意:列举的例子是不公平的,因为如果和网络不是简单的命令,但保留字见下面的评论。)
(Note: The cited example is not fair, since 'if' and 'fi' are not simple commands but reserved words. See comments below.)
这篇关于无法理解鱼shell命令替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!