Function 新定义的别名在函数(zsh)中不起作用

Function 新定义的别名在函数(zsh)中不起作用,function,alias,zsh,operator-precedence,Function,Alias,Zsh,Operator Precedence,我试图在zsh中的函数中定义并使用别名。它不起作用。究竟为什么不呢?我能绕开它吗 % cat > test alias_problem () { alias hithere="echo Hi there!" hithere } ^D % source test % alias_problem alias_problem:2: command not found: hithere % hithere Hi there! % wtf? zsh: no matches found: wt

我试图在zsh中的函数中定义并使用别名。它不起作用。究竟为什么不呢?我能绕开它吗

% cat > test
alias_problem () {
  alias hithere="echo Hi there!"
  hithere
}
^D
% source test
% alias_problem
alias_problem:2: command not found: hithere
% hithere
Hi there!
% wtf?
zsh: no matches found: wtf?
理想情况下,运行alias_problem会打印出
Hi
% cat > test
alias_problem () {
  alias hithere="echo Hi there!"
  hithere
}
^D
% source test
% alias_problem
alias_problem:2: command not found: hithere
% hithere
Hi there!
% wtf?
zsh: no matches found: wtf?
背景:我想做一个函数,创建几个别名,然后运行其中一个。差不多

myfuncA () {
  alias alias1=...
  alias alias2=...
  alias1
}
这样我就可以用几个命令设置一个环境。我将使用第二个函数将别名切换到不同的集合

我应该只使用函数吗?在zsh中,有什么理由对函数使用别名吗?我想知道发生了什么,只是想知道今后如何避免

谢谢:)


--彼得

这一点在《别名》下的
曼zshmisc
中提到:

别名通常会遇到以下问题: 以下代码:

          alias echobar=’echo bar’; echobar
这将打印一条消息,说明找不到echobar命令。发生这种情况的原因是,在编写代码时会展开别名 读入;整行都是一次性阅读的,所以 执行echobar时,扩展新定义的别名为时已晚。这通常是shell脚本中的一个问题, 函数,以及使用“源”或“.”执行的代码。 因此,建议在非交互式代码中使用函数而不是别名


我认为问题在于,函数体存储为一行(隐式为
别名heree=“…”;heree
),因此上述引用中遇到的相同情况适用。

因此,您(和zshmisc)说,如果已经定义了echobar,那么
ls;echobar;ls
扩展为
ls;回波条;ls
然后执行?我错过了;谢谢,好的。定义函数时读取代码,因此调用函数时不会进行别名扩展,尽管别名是为函数调用后读取的代码定义的。这样可以更清楚地看到:定义
foo(){bar;}
,然后定义别名
alias bar=“echo foo”
。调用
foo
仍然会产生命令未找到错误,因为调用函数时不会对函数体执行别名扩展。