0

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.

Yang Li
  • 1
  • 2
  • You might consider if a shell function is more appropriate than an alias in your situation. – chepner May 09 '13 at 12:28
  • 1
    Yes, a shell function if available will be useful, however, we cannot define functions in tcsh. – Yang Li May 10 '13 at 05:23
  • Is there any `bash` component to this question, then? – chepner May 10 '13 at 13:13
  • I bielive this applies to bash too. Defining a shell function is one solution for bash, while using eval is another elegant solution for both bash and tcsh, as pointed out by choroba below. – Yang Li May 11 '13 at 06:25

1 Answers1

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

choroba
  • 231,213
  • 25
  • 204
  • 289
  • I have updated the post about the more complex situation I meet. Could you please help check that? – Yang Li May 10 '13 at 05:34
  • @YangLi: `eval` does not run in a subshell. – choroba May 10 '13 at 22:58
  • YES, you are right, eval is the ultimate solution. Thanks a lot! – Yang Li May 11 '13 at 06:27
  • For those who are confused with exec, eval, and source in shell like me, I find a useful link: [link](http://www.unix.com/shell-programming-scripting/54347-bash-shell-exec-eval-source-looking-help-understand.html) – Yang Li May 11 '13 at 06:35