22
7
Just about every time I 'cd' to a different directory on my machine (in this case, running Mac OS X 10.6.7) via the command line (which is bash), I immediately type 'ls' to get the list of contents in that directory. I'm trying to figure out a way to override 'cd' so that it changes to the requested directory and then gives me the list in one shot.
I've been able to get the basic functionality I'm looking for working by with the following line added to my ~/.bash_profile
function cl() { cd "$@"; ls -l; }
This works as expected. Changing to the requested directory and then showing me the contents. Where I run into an issue is trying to override "cd" itself instead of creating a new "cl" command.
The following things do not work
##### Attempt 1 #####
# Hangs the command line
function cd() { cd "$@"; ls -l; }
##### Attempt 2 #####
# Hangs the command line
function cd() { 'cd' "$@"; ls -l; }
##### Attempt 3 #####
# Does not change directory.
# Does list contents, but of the directory where you started.
function cd() { /usr/bin/cd "$@"; ls -l; }
#### Other attempts that fail in various ways #####
alias cd=cd "$@"; ls -la;
alias cd="cd '$@'; ls -la;"
alias cd='cd "$@"'; ls -la;
alias cd=/usr/bin/cd "$@"; ls -la;
I also tried several other iterations that aren't listed as well as making an alias that points to the working 'cl' function. None of which worked.
What I've read in documentation talks about the fact that 'cd' can't be run as an external command (which is what I understand to be the way the function would need to use it).
So, I can currently use my "cl" command and get what I want, but the question is/remains:
Is there a way to override the behavior of 'cd' to have it change to the requested directory and then do something else afterward?
Doesn't work for a parameterless call. – Daniel Beck – 2011-06-13T16:04:17.917
3@DanielBeck - at least on my Mac OSX (10.6.7) it this is working fine with a parameterless call. The behavior is that it changes to the home directory and then does the list of that dir. Effectively duplicating the functionality of plain-old 'cd' with the new feature added at the end. – Alan W. Smith – 2011-06-13T17:04:27.403
2@Alan True, I tested that by writing that code ad-hoc into the shell. It seems the behavior of
cd ""
(to what this answer should evaluate is different fromcd "$@"
with empty$@
. Sorry about the confusion. – Daniel Beck – 2011-06-13T17:08:07.790@DanielBeck - no worries. – Alan W. Smith – 2011-06-13T17:15:58.450
2Note: I'm changing this to the accepted answer since it is a precise answer to the question. The one by @RichHomolka is great for addressing the principal, but this one is exactly what can be put in your ~/.bash_profile file. – Alan W. Smith – 2011-06-13T17:17:50.180
Why
builtin cd "$@"
instead ofbuiltin cd $*
? – Benoît – 2012-05-14T16:04:43.740