3

I want to change the behavior of the cd command so that it changes to a directory and lists the files in that directory, but I can't seem to get it to work.

I have tried the following with no success:

 % alias cd='cd $@; ls'

It lists the files of the directory as if it had changed directory but when it is done executing it leaves me in the same directory.

8
  • 1
    It's really crazy (IHMO) to override one of the key cmds in all of unix file-system navigation. At least use CD, or whynot some other 2 letter abberviation (LS)?. Good luck.
    – shellter
    Commented Nov 18, 2011 at 19:48
  • You aren't overriding it. You are telling bash to run cd ... && ls when you type in cd into your prompt.
    – Blender
    Commented Nov 18, 2011 at 19:51
  • as long as you don't alias unalias you can easily revert...
    – hafichuk
    Commented Nov 18, 2011 at 19:58
  • Or just re-open your Terminal emulator ;)
    – Blender
    Commented Nov 19, 2011 at 0:45
  • 1
    Possible duplicate of Alias to CD in a directory and call a command
    – muru
    Commented Oct 22, 2018 at 9:16

1 Answer 1

5

I use this in by .bashrc:

function cd {
    builtin cd "$@" && ls
}

To disable it, you could try overriding it inside of your script:

function cd {
    builtin cd "$@"
}
6
  • +1, beat me to it. There's no way you can do this with an alias.
    – Fred Foo
    Commented Nov 18, 2011 at 19:48
  • I was wondering, I have to sometimes run some scripts that use cd.. now I would like to disable it for those. How could I remove this functionality on those scripts
    – Flethuseo
    Commented Nov 19, 2011 at 0:43
  • Override it. See my comment.
    – Blender
    Commented Nov 19, 2011 at 0:45
  • 3
    @Flethuseo: You remove a shell function with the unset command: unset cd in your case.
    – camh
    Commented Nov 19, 2011 at 2:44
  • 1
    Its very important that if you do this that you put it in .bashrc instead of .bash_profile or .profile. .bashrc is only meant to be read when you have an interactive shell and thus your override won't get used by scripts that use 'cd'. Otherwise, you're probably going to break something.
    – deltaray
    Commented Nov 20, 2011 at 3:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .