2

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.

migrated from stackoverflow.com Nov 19 '11 at 1:52

This question came from our site for professional and enthusiast programmers.

  • 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 Nov 18 '11 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 Nov 18 '11 at 19:51
  • as long as you don't alias unalias you can easily revert... – hafichuk Nov 18 '11 at 19:58
  • Or just re-open your Terminal emulator ;) – Blender Nov 19 '11 at 0:45
  • 1
    Possible duplicate of Alias to CD in a directory and call a command – muru Oct 22 '18 at 9:16
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 "$@"
}
  • +1, beat me to it. There's no way you can do this with an alias. – Fred Foo Nov 18 '11 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 Nov 19 '11 at 0:43
  • Override it. See my comment. – Blender Nov 19 '11 at 0:45
  • 3
    @Flethuseo: You remove a shell function with the unset command: unset cd in your case. – camh Nov 19 '11 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 Nov 20 '11 at 3:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.