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.

Flethuseo
  • 173

1 Answers1

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 "$@"
}
Blender
  • 1,873
  • 2
  • 18
  • 25
  • +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 00:43
  • Override it. See my comment. – Blender Nov 19 '11 at 00:45
  • 3
    @Flethuseo: You remove a shell function with the unset command: unset cd in your case. – camh Nov 19 '11 at 02: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 03:32
  • I dont' need to use a function name of cd, but with cdd, but I am getting syntax error line 16: syntax error near unexpected token 'builtin'. The full code is function cdd{ builtin cd "$@" && ls } – R Nanthak Oct 06 '21 at 08:49