A newly defined alias within another alias, the fi

2019-08-18 09:00发布

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条回答
Luminary・发光体
2楼-- · 2019-08-18 09:24

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

查看更多
登录 后发表回答