[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: aliases sometimes not expanded even with expand_aliases set
From: |
Greg Wooledge |
Subject: |
Re: aliases sometimes not expanded even with expand_aliases set |
Date: |
Sat, 12 Oct 2024 09:47:01 -0400 |
On Sun, Oct 13, 2024 at 00:01:10 +1030, ian@beware.dropbear.id.au wrote:
> In the following script, the first alias fails with "comand not found"
> but the second works.
>
> #!/bin/bash
>
> shopt -s expand_aliases
>
> if :; then
> alias foo='echo'
> foo x y z
> shopt expand_aliases
> alias -p
> fi
You've got a compound command there, from "if" to "fi". The parser has
to read the entire compound command and parse it before any part of it
can be executed.
The "foo" alias is not defined at the time the compound command is parsed,
so the "foo x y z" line does not undergo the alias expansion. It's parsed
as a command named "foo" with three argument words.
You'll see the same behavior if you try to define an alias inside a
function and then use it in the same function. The function body is a
compound command, so it gets parsed all at once.
Alias definitions (and anything else that affects parsing, such as the
extglob option) should appear outside of compound commands. Personally,
if I had to use one, I'd put it in the same place as my function
definitions.