2

From bash manual

Aliases are expanded when a function definition is read, not when the function is executed, because a function definition is itself a compound command. As a consequence, aliases defined in a function are not available until after that function is executed. To be safe, always put alias definitions on a separate line, and do not use alias in compound commands.

I understand there might be some potential problem of using alias in a function definition, although still have some doubts about Which of the following shell operations are performed inside the function body when running a function definition and when calling a function?.

But why does "do not use alias in compound commands" generalize from function definitions to general compound commands?

What other kinds of compound commands can have what kinds of problems with alias?

4

But why does "do not use alias in compound commands" generalize from function definitions to general compound commands?

It's the other way round (your excerpt of the bash manual is not complete). Compound commands generalize to function definitions which are compound commands.

A compound command is executed once it is completely read. Aliases are defined when they are executed, not when they are read (obviously). But alias substitution only takes place when the command is read.

Take this compound command for example:

$ alias echo='echo Follow my advice:' &&
> echo Alias is a basic substitution mechanism
Alias is a basic substitution mechanism

$ echo Use aliases sparingly
Follow my advice: Use aliases sparingly

First, you can see that since && introduces a compound command, the shell does not execute anything and prompts for a second line of input.

When this two-line compound command is read, aliases are substituted before the command is executed. At the time of this substitution, the echo alias does not exist yet, therefore nothing is substituted. Finally, when the whole command is executed, this is the builtin echo command that is used, even though it comes after the alias definition.

When the second echo command is read, the echo alias exists and is substituted. The command that is executed is therefore echo Follow my advice: Use aliases sparingly.

Function definition is a bigger kind of compound command but the functioning is the same. Any inner alias definition only takes effect when the function is called.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.