Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: When it is allowed to use alias after defining it?



On Fri, 2022-12-30 at 21:45 +0000, Sebastian Gniazdowski wrote:
> I was thinking that in current file it is impossible to use an alias – only should work in sourced sub-script. 
> 
> So:
> alias q=pushd
> # Expected to not work
> q
> # Expected to work
> source ./using-q.zsh
> 
> The script is fine to use q. Is that the truth? Because I'm using
> aliases in the same file, only if it is at some proximity from
> definition. What are the rules here?

It's a question of when the execution of the line happens in relation to
parsing it, and also of the fact that expanding an alias happens very
early at the point where the line is read in.

When reading a script, the shell reads one line at a time --- if the
line contains an unfinished complex command, it will continue reading
until that's finished.  Then it executes it, before reading anything
else, so if the line was an alias definition that's available from then
on.  That's pretty much the same as what happens in an interactive
shell, in fact it's the same internal logic --- the difference between
the two occurs at the point where the shell gets input, where it decides
whether it's blindly going to read a line or invoke the editor.

So complex commands are the key case where the effect is delayed.  This
obviously includes functions; the classic case where you *can't* rely on
an alias being defined is:

fn() {
  alias q=pusehd
  q
}

since the function is defined in one go before the alias is defined
within the function.  Because aliases are resolved on input, the q is
treated as a normal command within the function.

Although this is a logical consequence of shell input, it's certainly
not an obvious one.

pws





Messages sorted by: Reverse Date, Date, Thread, Author