Whenever I cd
into a directory, the next thing I spontaneously do - listing the contents of that directory using ls
command. I don't know if all of you do this, but I guess some of you might have this habit. It would be better if we combine the functionality of the cd and ls in one command, wouldn't it? This brief guide explains how to list directory contents automatically whenever you cd into it in Linux.
How to cd and ls in one command in Bash
Please note that I am not talking about the one-liner commands. For instance, you can perform cd and ls with a single-line command like below.
cd path-to-dir && ls
Or,
cd path-to-dir ; ls
Yes, It does work! But it is not the scope of this guide. We will do it with the help of a simple BASH function. This trick will work in all Linux and Unix-like distributions that supports BASH.
Open your ~/.bashrc
file in your favorite editor:
nano ~/.bashrc
Add the following lines at the end:
cdls() { local dir="$1" local dir="${dir:=$HOME}" if [[ -d "$dir" ]]; then cd "$dir" >/dev/null; ls --color=auto else echo "bash: cdls: $dir: Directory not found" fi }
Here, I used the function name as cdls ()
for the sake of the easy remembering! You can name this function however you please. Also replace ls --color=auto
parameter with your own. Save and close the file.
Run the following command to take effect the changes.
source ~/.bashrc
Now list the directory contents automatically whenever you cd into it like below.
Example:
$ cdls /var/log/ alternatives.log btmp dpkg.log kern.log syslog wtmp apt cloud-init.log faillog landscape syslog.1 auth.log cloud-init-output.log installer lastlog tallylog bootstrap.log dist-upgrade journal lxd unattended-upgrades sk@ubuntuserver:/var/log$ pwd /var/log
You can also add the following much simpler function in your ~/.bashrc
file.
cdls() { cd "$@" && ls; }
Source the ~/.bashrc
file to take effect the changes. Also don't use both functions at the same time with same name. Either use one function or use different name (E.g. cdls
and cl
) for each function.
Before I knew this trick, I usually do:
cd /var/log/
And then;
ls
Or,
cd /var/log/ && ls
Not anymore! Now I can be able to list any directory contents whenever I cd into it. This is handy when you're working with large number of directories often.
One big disadvantage of this trick is you will have to wait a few seconds to several minutes when cd into a directory that contains hundreds and thousands of files. In such cases, use the normal cd
command.
Suggested Read:
4 comments
Hi,
Very Useful function(cdls)
Thanks a lot
Most (all?) shells accept ‘;’ as seperation between commands
bash$ cd ~; ls
this is not a single command – its 2 commands seperated by the AND operator
Yes, we include the 2 commands in a BASH function and run it as single command.