I have this setup file:

function latest { 
    count=${1:-5} ; 
    echo "Just changed"
    ls -lrtd * | tail -$count ; 

I call it:

. setup

Then I ask bash if the latest function is defined:

>type latest
latest is a function
latest () 
    echo "Just changed";
    ls --color=auto -lrtd * | tail -$count

Just changed is an arbitrary string that I used to make sure I was not looking at a definition of latest from another file.

And the question is: why is Bash adding the --color=auto to the ls command (where it is of no use since the output is piped anyway). And yes, on my shell ls is aliased to ls --color=auto, and if I remove the alias this doesn't happen. But I thought aliases where not used in functions and in any case this substitution happened at function definition time?


You've observed documented behavior; in the Alias section of the bash manual:

Aliases are expanded when a function definition is read, not when the function is executed, because a function definition is itself a command.

| improve this answer | |

Jeff is correct above. To see the aliases defined in your shell, type "alias" at the prompt.


[USERID ~] $ alias
alias l.='ls -d .* --color=auto'
alias ll='ls -ahlF'
alias ls='ls --color=auto'
alias vi='vim'
[USERID ~] $

To avoid the alias in your script, you would need to either unalias the "ls" command or call it directly. To find the location of "ls", use the type shell builtin:

[USERID ~] $ type -P ls

You could put that in a variable and call "ls" using the variable:

[USERID ~] $ lsCmd=$(type -P ls)
[USERID ~] $ echo $lsCmd
[USERID ~] $ ls
MyAppData  MyDocuments  MyDownloads  Scripts  tmp.VOOlcGffwf  tmp.Y6IE7S2ps4
[USERID ~] $ $lsCmd
MyAppData  MyDocuments  MyDownloads  Scripts  tmp.VOOlcGffwf  tmp.Y6IE7S2ps4

In the first case, calling just "ls" gives the output in color because "ls" is aliased to "ls --color=auto" but the second case give the output without color as the alias is bypassed.

| improve this answer | |

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.