Linux “cd” tips

cd (change directory) is one of the most frequently used commands in Linux. It’s the navigating command through which we walk along different branches of the file system hierarchy. The following much needed tricks are from the awesome book Linux 101 Hacks by Ramesh Natarajan.

1. Define the reference directory in CDPATH
This one is a major productivity boost. When you frequent some directories more than others, you can add that directory to CDPATH. cd now changes directories to the ones below that defined in the CDPATH.

root@kali:~# export CDPATH=/etc
root@kali:~# cd network
root@kali:/etc/network# pwd

Notice the directory network is searched under /etc.

Just like PATH, you can add multiple paths to CDPATH.

export CDPATH=.:~:/etc:/opt

2. Add aliases to enhance cd ..
These aliases I find handy to navigate immediate and higher parent directories.

alias ..="cd .."
alias ...="cd ../../"
alias ....="cd ../../../"
alias .....="cd ../../../../"
alias ......="cd ../../../../../"

3. Combine mkdir and cd together (mkdircd)
Add this one liner to .bashrc and you have an handy command which will cd into the directory you create.

function mkdircd () { mkdir -p "$@" &&  eval cd "\"\$$#\"" ; }

4. Directory stack : dirs, pushd, popd
Directory stack helps if you know the directories you’ll navigate beforehand.
dirs –> dispalys the content of the stack. The first item displayed is always the current directory.
pushd –> pushes the directory into the stack and cd’s into it.
popd –> pops the top directory of the stack and cd’s into it.


5. Toggle between the last two directories accessed
cd – will cd’s to the last accessed directory.

root@kali:/etc# cd ~
root@kali:~# cd -

6. Auto correct the typos
shopt -s cdspell will auto correct the misspelled directory names.

root@kali/etc:~# cd netwokr
bash: cd: netwokr: No such file or directory
root@kali:/etc#shopt -s cdspell
root@kali:/etc# cd netwokr



About Deepak Devanand

Seeker of knowledge
This entry was posted in Linux, Uncategorized and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s