Ubuntu – How to create an alias for cd and ls

aliasbashcommand line

I frequently run the ls command after running the cd command. How can I create an alias (like cs) for this operation?

Best Answer

From Bash Tips and Tricks: 'cd' with style:

Finally, I want to show you how to write your own custom replacement for the 'cd' command.

Do you find yourself always typing the same thing upon changing into a directory? You probably at least list the files there every time, perhaps so much that your hands automatically type 'ls' after every 'cd'.

Well, by trying every way I could think of, it turns out there's only one way to properly accomplish the goal we're seeking. We have to create a shell function.

Shell functions are part of shell programming. Like in compiled programming languages, functions provide a sort of procedural modularizability. One can create a generic function to perform an often-used bit of logic or computation with different parameters. In this case, the parameter is the current working directory.

Here's a simple one:

function cs () {
    cd $1
    ls
}

As @geirha corretly notes, the above function will fail if you try to switch to a directory with a space in its name:

$ cs A\ B/
-bash: cd: A: No such file or directory
<current directory listing>  

You should instead use the following function:

function cs () {
    cd "$@" && ls
    }

Once you add that code to your ~/.bashrc, you should be able to do this:

hello@world:~$ cs Documents/
example.pdf tunafish.odt
hello@world:~/Documents$