2

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 Answers3

4

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; }
Flint
  • 3,201
1

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.

0

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.

LnxSlck
  • 12,456