Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot understand command substitution in Fish shell

In sh:

~$ `echo ls`
bin/  Desktop/

But in fish:

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?

Well, the help doc does say

If a parameter contains a set of parenthesis, the text enclosed by the parenthesis will be interpreted as a list of commands.

But still, why?

like image 316
weakish Avatar asked Jul 19 '10 13:07

weakish


1 Answers

Update

This answer was written ten year ago in 2010. Recent versions of fish (I tested on 3.1.2) updated and set cmd ls; $cmd is valid now.

How

This because command substitutions belong to parameter expansions and are not allowed as commands.

A similar example:

in sh:

tmpls=ls
$tmpls

But in fish:

% set cmd ls; $cmd
fish: Variables may not be used as commands.
...

Why

In short, it's good for verifiability

This article explains details:

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

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; }

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.)

like image 58
weakish Avatar answered Sep 19 '22 13:09

weakish