Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I don't have many aliases set up in my .bash_aliases file just yet. Only recently have I discovered how useful they can be.

I can see myself getting quite hooked on aliases so before the file gets too unwieldy I'd like to clarify something by asking a very simple question. Does one alias affect another, or does the alias always revert back to the original command?

An example may make this more clear:

I have ls aliased to ls -lF. Let's say I'd like to also alias d to ls -l | grep -E "^d": does d now use ls -lF in place of ls? If so, is it a matter of order in the .bash_aliases configuration file?

man alias didn't enlighten me.

share|improve this question
add comment

1 Answer 1

up vote 11 down vote accepted

From Aliases (section 6.6 of the Bash Manual):

The first word of each simple command, if unquoted, is checked to see if it has an alias. If so, that word is replaced by the text of the alias.

This happens when you use the alias, not when you define it. Here's an example:

$ alias a1='a2 hello'
$ alias a2='echo'
$ a1
hello
$ unalias a2
$ a1
bash: a2: command not found
share|improve this answer
    
OK great, thanks for that example (and also for the link to the Bash Manual). I quote from the Manual: "The rules concerning the definition and use of aliases are somewhat confusing... For almost every purpose, shell functions are preferred over aliases." I guess I'd better learn how to do shell functions then. :) –  boehj Apr 27 '11 at 20:53
    
Yes. Aliases can save you some typing for common commands, but for anything even remotely complex writing custom functions to handle it is usually a better option. –  Caleb Apr 27 '11 at 21:28
    
@Caleb @Gilles - Thank you folks. BTW, ls='ls --color' I can see being very handy. Love this site.:) –  boehj Apr 27 '11 at 21:50
    
@boehj: A rule of thumb is to use an alias when you want to have automatic arguments to a command, using the name of the command or a minor variation, and functions otherwise. So alias ls='ls --color', alias cp='cp -i', but functions for more complex stuff. In particular, I'd make your d a function so that you can pass arguments to ls. [comment reposted to fix confusing braino, thanks @cjm] –  Gilles Apr 27 '11 at 22:48
    
@Gilles - OK, my task for today is to teach myself how to replicate d as a shell function. –  boehj Apr 27 '11 at 23:04
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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