A newly defined alias within another alias, the first excution will fail

自古美人都是妖i 提交于 2019-12-25 02:01:46

问题


If we define and use an alias B within another alias A, the first time execution of A will fail. For example,

alias A='alias B="which ls"; B;'

The first time excution would look like (in bash)

bash: B: command not found

The example above is a simplified construction. in practice, we might meet such usage implicitly.

The reason might be: when we execute the alias A, all expansions are carried out before execution, but B is undefined when we execute A for the first time.

So is there a way to make the first time execution successful?

The situation I met is more complex than above. My alias looks like (in tcsh)

alias A 'cmd1; cmd2; B -v arg_of_B; cmd3; cmd4;'

where, B is an alias defined by cmd2. In addition, the definition of B looks like (in tcsh)

alias B 'source /path/to/script.csh'

So using eval to postpone the execution of B might not work, because eval will fork a new shell to execute the command. Another factor making this more complex is there are arguments following the alias. I tried to use exec but without achieving success.


回答1:


The problem can be simplified to a simple alias. The following fails for the first time as well:

alias A=ls ; A

To postpone the expansion, you can use eval:

alias A=df ; eval A

(Tested in bash and tcsh).



来源:https://stackoverflow.com/questions/16459920/a-newly-defined-alias-within-another-alias-the-first-excution-will-fail

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!