Say I have command A
and command B
but I want B
to run when I type A
and vice versa. I've tried
alias A='B'
alias B='A'
But this doesn't seem to work for some reason.
How do I do this?
EDIT:
Command B
has actually been defined as a function in my .bashrc
, so
alias A='command B'
alias B='command A'
doesn't work as suggested.
I guess I could update the question to say that A
and B
could also be functions defined in bash.
Best Answer
So you can get explicit about the way the shell goes about locating commands in a few different ways. You can use...
...to instruct the shell only to invoke the command_name if it is a
$PATH
d executable. This is important in cases like yours because, when you've finishedalias A
refers toalias B
which refers toalias A
usually something like 20 times before thealias
expansion quits recursing - and which lands you right back where you started. If you wanted to definitely only invoke a$PATH
d executableB
when callingA
and vice versa you can do......which should avoid even calling functions named
A
orB
. Otherwise - because the shell will not expand a quotedalias
as analias
but will still call a function even if its command_name is quoted you can quoteA
andB
in the definitions like...Ok, so it doesn't recurse twenty times. I could swear I had read that in some
man
page, but I guess it is at least not true of eitherbash
orksh
(having tested only either of them so far). It, in fact, recurses only twice:If I do the above and do...
...in
bash
it prints:I guess this is relevant to this from the
bash
manual:ls
tols -F
, for instance, andbash
does not try to recursively expand the replacement text.I had read that before, but I didn't think it would test all expansions leading up to the current expansion when doing so - I figured it would only apply to the latest expansion in the chain. Anyway, that appears to be why.
I did note some interesting behavior otherwise though. After I had already declared both the aliases and the functions I went to rerun the commands, but with a little less intervening white space - like this:
...and that did...
Which means that the shell substituted the alias contents in for the function name - which is not a position one might normally expect an expansion to occur - did the
echo
s and still redefined then executed the functions.