0

Every time I type cd folder or cd .. I would like it to immediately run ls after.

Is there a way to do that?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
airborne snow
  • 39
  • 1
  • 5
  • I suggest to use a function. – Cyrus Jun 24 '21 at 14:24
  • See: [alias - cd followed by ls](https://stackoverflow.com/q/14146530/3776858) – Cyrus Jun 24 '21 at 14:25
  • @airbornesnow: The question, as you wrote it, does not make sense. An alias is not bound to a _terminal_, but to the _shell_. Further, you are not clear in which shell you are using, as you are tagging the question as _zsh_ and as _bash_. – user1934428 Jun 24 '21 at 14:45

2 Answers2

2

Reposting the answer from another post

Put this in .zshrc to create alias for cl:

#print contents after moving to given directory
cl()
{
    cd $@
    ls
}

To override cd (not recommended), put this in .zshrc:

#print contents after moving to given directory
cd()
{
    builtin cd $@
    ls
}
Cyrus
  • 84,225
  • 14
  • 89
  • 153
airborne snow
  • 39
  • 1
  • 5
0

I strongly recommend against overriding cd itself but essentially what you would like to do is:

alias cdl='cd $*; ls'

Here cdl is the name of your new command (it could also be cd if you really insist) and then you are assigning it to another command, which is itself a sequence of two commands:

  • cd $* where $* refers to all the arguments you are passing to cdl
  • ls You could condition the execution of ls on the success of cd i.e. only run it if cd is given a valid folder and just do nothing otherwise:
alias cdl='cd $* && ls'

UPDATE

@Cyrus, you are right, this doesn't work from within an alias (though it does if you just run from from the command line directly). This works though:

alias cdl='ls $*; cd $*'
rudolfovic
  • 3,163
  • 2
  • 14
  • 38