Frage

Zsh is a very powerful shell, but once in a while I get surprised as it goes one step too far.

Recently I've had one of these surprisingly puzzling moments after typing the following commands (adapted for simplicity and clarity):

% echo "nosuchfunction() nosuchcommand"
nosuchfunction() nosuchcommand

% echo nosuchfunction() nosuchcommand

% echo "nosuchfunction() nosuchcommand"
echo:3: command not found: nosuchcommand

% echo I used to like this
echo:4: command not found: nosuchcommand

It took me a while to understand what was going on and that this was specific to zsh and not the command I was trying to execute. At line 2 I've created some sort of inline function that got assigned to "echo". At least that's the only explanation that makes sense in the light of the output of lines 3 and 4.

As a comparison, in bash things make a little bit more sense:

% echo "nosuchfunction() nosuchcommand"
nosuchfunction() nosuchcommand

% echo nosuchfunction() nosuchcommand
bash: syntax error near unexpected token `('

% echo "nosuchfunction() nosuchcommand"
nosuchfunction() nosuchcommand

% echo I used to like this
I used to like this

At this point I'm also not sure if this is supposed to be a feature or a bug, but I would simply like to disable this behavior.

Anyone knows how?

War es hilfreich?

Lösung

Actually you created two functions, echo and nosuchfunction, both executing nosuchcommand.

zsh allows not only 'inline function definition' (as in: you do not need to use braces or parenthis if your function contains only one command), but also allows for multiple names given to the same function. From zshmisc(1):

function word ... [ () ] [ term ] { list }
word ... () [ term ] { list }
word ... () [ term ] command
     where term is one or more newline or ;.  Define a function which is
     referenced by any one of word.  Normally, only one word is provided;   
     multiple  words  are  usually  only useful for setting traps.  The 
     body of the function is the list between the { and }.  See the
     section `Functions'.

This issue can be somewhat avoided by disabling the MULTI_FUNC_DEF option (unsetopt multifuncdef), which allows the definition of multiple functions without the function keyword. As noted in the manpage zshoptions(1) for MULTI_FUNC_DEF:

Multiple function definitions are not often used and can cause obscure errors.

Aside from that it is best to remember that parenthesis are syntactic elements, in zsh as well as in bash, and if you do not want to use them as such you have to quote them. (It is not as if the second line did work in bash, so just disabling 'inline definitions' would not solve anything anyway.)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top