Most of the time when I do a cd
command I also do a ls
to see what other files or folder are in that directory. So I want to execute ls
everytime I change the directory. I know I can do cd foo && ls
but is it really necessary to do && ls
everytime?
3 Answers
There are 2 ways to do this. You can create an alias as LnxSlck posted or another one is creating a function in .bash_aliases
mycd(){ cd "$1" && ls; }
-
-
1Make sure to quote the parameter expansion, otherwise it will fail if the directory contains special characters, like whitespace.
mycd() { cd "$1" && ls; }
– geirhaJul 11, 2012 at 7:18
I use the following, which doesn't involve adding any new commands:
cd() {
builtin cd "$@"
local status=$?
[ $status -eq 0 ] && ls
return $status
}
This makes cd
work the same as before, except that there's also an ls
.
Note the following implications: The other examples don't permit arguments to cd
. While admittedly those arguments are uncommon, this is a 100% compatible drop-in replacement. And because it returns cd
's exit status, it won't break scripts.
There's one caveat here. If you ever don't want this functionality, you have to call builtin cd
. But my experience in using this function for many years is that such occurrances are rare, occurring primarily in scripts, and the convenience of not having to type something long like mycd
every time you want to change directories greatly outweighs the minor drawback of typing builtin cd
once in a blue moon.
You can make an alias
for cd
, and add it to your *bash_profile* or bashrc, something like:
alias 'mycd'='cd $1 && ls'
put that in your .bashrc
. It is however recommended that you store all your aliases in ~/bash_aliases
file, so create the file using touch ~/.bash_aliases
if it's not already present and use it to store all your aliases.
-
1It's recommended that you add aliases to
~/.bash_aliases
. That way it stays separate from rest of the config files :) Jul 11, 2012 at 4:01 -
its doing the
ls
part (when I domycd Desktop
, it prints the desktop), but isn't changing the directory to desktop. Jul 11, 2012 at 4:13 -
1I guess that doesn't work because in alias you can't have another command after param or else it will be taken as input for the param.
alias foo='echo $1 && echo bar'
,foo moo
outputsbar moo
instead of expectedmoo bar
– FlintJul 11, 2012 at 4:45 -
You need a shell function here. Aliases aren't up to the task. Jul 11, 2012 at 23:07