This article is part of the ongoing Productivity Tips for Geeks series. cd is one of the most frequently used command during a Unix session. In this article, I’ve provided 6 cd command hacks, which will boost your productivity instantly and make it easier to navigate the directory structure from command line.
Hack #1: Use CDPATH to define the base directory for cd command
If you are frequently doing cd to subdirectories of a specific parent directory, you can set the CDPATH to the parent directory and perform cd to the subdirectories without giving the parent directory path as explained below.
[ramesh@dev-db ~]# pwd /home/ramesh [ramesh@dev-db ~]# cd mail -bash: cd: mail: No such file or directory [Note: This is looking for mail directory under current directory] [ramesh@dev-db ~]# export CDPATH=/etc [ramesh@dev-db ~]# cd mail [Note: This is looking for mail under /etc and not under current directory] [ramesh@dev-db /etc/mail]# pwd /etc/mail
To make this change permanent, add export CDPATH=/etc to your ~/.bash_profile
This hack can be very helpful under the following situations:
- Oracle DBAs frequently working under $ORACLE_HOME, can set the CDPATH variable to the oracle home
- Unix sysadmins frequently working under /etc, can set the CDPATH variable to /etc
- Developers frequently working under project directory /home/projects, can set the CDPATH variable to /home/projects
- End-users frequently accessing the subdirectories under their home directory, can set the CDPATH variable to ~ (home directory)
Hack #2: Use cd alias to navigate up the directory effectively
When you are navigating up a very long directory structure, you may be using cd ..\..\ with multiple ..\’s depending on how many directories you want to go up as shown below.
# mkdir -p /tmp/very/long/directory/structure/that/is/too/deep # cd /tmp/very/long/directory/structure/that/is/too/deep # pwd /tmp/very/long/directory/structure/that/is/too/deep # cd ../../../../ # pwd /tmp/very/long/directory/structure
Instead of executing cd ../../../.. to navigate four levels up, use one of the following alias methods:
Navigate up the directory using ..n : In the example below, ..4 is used to go up 4 directory level, ..3 to go up 3 directory level, ..2 to go up 2 directory level. Add the following alias to the .bash_profile and re-login.
alias ..="cd .."
alias ..2="cd ../.."
alias ..3="cd ../../.."
alias ..4="cd ../../../.."
alias ..5="cd ../../../../.."
# cd /tmp/very/long/directory/structure/that/is/too/deep
#..4
[Note: use ..4 to go up 4 directory level]
# pwd
/tmp/very/long/directory/structure/
Navigate up the directory using only dots: In the example below, ….. (five dots) is used to go up 4 directory level. Typing 5 dots to go up 4 directory structure is really easy to remember, as when you type the first two dots, you are thinking “going up one directory”, after that every additional dot, is to go one level up. So, use …. (four dots) to go up 3 directory level and .. (two dots) to go up 1 directory level. Add the following alias to the .bash_profile and re-login for the ….. (five dots) to work properly.
alias ..="cd .."
alias ...="cd ../.."
alias ....="cd ../../.."
alias .....="cd ../../../.."
alias ......="cd ../../../../.."
# cd /tmp/very/long/directory/structure/that/is/too/deep
# .....
[Note: use ..... (five dots) to go up 4 directory level]
# pwd
/tmp/very/long/directory/structure/
Navigate up the directory using cd followed by consecutive dots: In the example below, cd….. (cd followed by five dots) is used to go up 4 directory level. Making it 5 dots to go up 4 directory structure is really easy to remember, as when you type the first two dots, you are thinking “going up one directory”, after that every additional dot, is to go one level up. So, use cd…. (cd followed by four dots) to go up 3 directory level and cd… (cd followed by three dots) to go up 2 directory level. Add the following alias to the .bash_profile and re-login for the above cd….. (five dots) to work properly.
alias cd..="cd .."
alias cd...="cd ../.."
alias cd....="cd ../../.."
alias cd.....="cd ../../../.."
alias cd......="cd ../../../../.."
# cd /tmp/very/long/directory/structure/that/is/too/deep
# cd.....
[Note: use cd..... to go up 4 directory level]
# pwd
/tmp/very/long/directory/structure
Hack #3: Perform mkdir and cd using a single command
Sometimes when you create a new directory, you may cd to the new directory immediately to perform some work as shown below.
# mkdir -p /tmp/subdir1/subdir2/subdir3 # cd /tmp/subdir1/subdir2/subdir3 # pwd /tmp/subdir1/subdir2/subdir3
Wouldn’t it be nice to combine both mkdir and cd in a single command? Add the following to the .bash_profile and re-login.
function mkdircd () { mkdir -p "$@" && eval cd "\"\$$#\""; }
Now, perform both mkdir and cd at the same time using a single command as shown below:
# mkdircd /tmp/subdir1/subdir2/subdir3
[Note: This creates the directory and cd to it automatically]
# pwd
/tmp/subdir1/subdir2/subdir3
Hack #4: Use “cd -” to toggle between the last two directories
You can toggle between the last two current directories using cd – as shown below.
# cd /tmp/very/long/directory/structure/that/is/too/deep # cd /tmp/subdir1/subdir2/subdir3 # cd - # pwd /tmp/very/long/directory/structure/that/is/too/deep # cd - # pwd /tmp/subdir1/subdir2/subdir3 # cd - # pwd /tmp/very/long/directory/structure/that/is/too/deep
Note: You can also substitute an argument from other commands in the history to the cd command using example#12 and #13 mentioned in the command line history examples article.
Hack #5: Use dirs, pushd and popd to manipulate directory stack
You can use directory stack to push directories into it and later pop directory from the stack. Following three commands are used in this example.
- dirs: Display the directory stack
- pushd: Push directory into the stack
- popd: Pop directory from the stack and cd to it
Dirs will always print the current directory followed by the content of the stack. Even when the directory stack is empty, dirs command will still print only the current directory as shown below.
# popd -bash: popd: directory stack empty # dirs ~ # pwd /home/ramesh
How to use pushd and popd? Let us first create some temporary directories and push them to the directory stack as shown below.
# mkdir /tmp/dir1 # mkdir /tmp/dir2 # mkdir /tmp/dir3 # mkdir /tmp/dir4 # cd /tmp/dir1 # pushd . # cd /tmp/dir2 # pushd . # cd /tmp/dir3 # pushd . # cd /tmp/dir4 # pushd . # dirs /tmp/dir4 /tmp/dir4 /tmp/dir3 /tmp/dir2 /tmp/dir1 [Note: The first directory (/tmp/dir4) of the dir command output is always the current directory and not the content from the stack.]
At this stage, the directory stack contains the following directories:
/tmp/dir4 /tmp/dir3 /tmp/dir2 /tmp/dir1
The last directory that was pushed to the stack will be at the top. When you perform popd, it will cd to the top directory entry in the stack and remove it from the stack. As shown above, the last directory that was pushed into the stack is /tmp/dir4. So, when we do a popd, it will cd to the /tmp/dir4 and remove it from the directory stack as shown below.
# popd # pwd /tmp/dir4 [Note: After the above popd, directory Stack Contains: /tmp/dir3 /tmp/dir2 /tmp/dir1] # popd # pwd /tmp/dir3 [Note: After the above popd, directory Stack Contains: /tmp/dir2 /tmp/dir1] # popd # pwd /tmp/dir2 [Note: After the above popd, directory Stack Contains: /tmp/dir1] # popd # pwd /tmp/dir1 [Note: After the above popd, directory Stack is empty!] # popd -bash: popd: directory stack empty
Hack #6: Use “shopt -s cdspell” to automatically correct mistyped directory names on cd
Use shopt -s cdspell to correct the typos in the cd command automatically as shown below. If you are not good at typing and make lot of mistakes, this will be very helpful.
# cd /etc/mall
-bash: cd: /etc/mall: No such file or directory
# shopt -s cdspell
# cd /etc/mall
# pwd
/etc/mail
[Note: By mistake, when I typed mall instead of mail,
cd corrected it automatically]
If you liked this article, please bookmark it on del.icio.us, and Stumble it.
Comments on this entry are closed.
Excellent tips. I have become a big fan of your blog. Thanks very much for all the good postings.
I would like to add: You can add more than one entries to the CDPATH variable, the same way you do with the PATH: separate them using colons. For example:
export CDPATH=.:~:~/src:/etc
I’ve had `cd..` aliased for a while because I always miss the space, but I never thought to extend it. Neat ideas 🙂
What do you always do after a “cd”?
Well… At least I do an “ls”.
function cd()
{
builtin cd ${1:-$HOME} && ls;
}
I’m not a big fan of aliases, so for #3 (going into a just created directory), I usually do
# mkdir /tmp/subdir1/subdir2/subdir3
# cd !$
You may also want to look at cdargs (http://www.skamphausen.de/cgi-bin/ska/CDargs). It saves you from most of those kludges (like CDPATH – a good way to shoot yourself in the foot when you accidentally cd into a different directory than you expected!).
Regards,
Jan
Directory stacks are quite useful, as you say.
I’ve found myself needing to
o see the stack and to
o move around in it more quickly.
So, ~/.bashrc gets the following valuable single character aliases beyond ‘m’ for less and ‘c’ for bzip2
alias d=’dirs -v’ # to get a listing of directories on the stack
alias 1=’pushd +1′ # roll the stack to get to the specified directory
alias 2=’pushd +2′
etc. My stacks often get up to 9 or 10 deep where these kinds of aliases help in moving around.
Hack #6 is lovely. Thanks. 🙂
A couple of suggestions included:
add the following alias to the .bash_profile and re-login…
If you put the alias(es) in ~/.bashrc, you can ‘source ~/.bashrc’ to (a) apply the alias(es) immediately without logging out and back in, and (b) confirm that the alias(es) won’t break anything, which can be difficult to fix if you can’t log back in.
I’m not sure, but I believe you can also ‘source ~/.bash_profile’.
In TCSH:
1) you also have a shell variable implicitcd so you don’t need to type ‘cd’ at all.
2) alias cd to pushd, and set the shell variables pushdtohome and pushdsilent. cd now behaves as usual but now if you type ‘dirs -v ‘ (alias this to d), you get a stack of all the directories you’ve been to. You can easily cd back to those by typing ‘cd =1/’ etc.
3) Also, alias pwd to p.
4) In TCSH, use bindkey to bind ‘Alt-p’ to pwd.
Eval? What’s wrong with function mcd(){ mkdir -p $* && cd $* }
agree with Sam however quotes are important there, I recommend this way:
mcd() { mkdir -p “$1” && cd “$1”; }
the latter won’t have problems with spaces on the argument.
as for the cd alias, instead of defining several ones it might be better to use a function too:
..() {
local levels=$1
while ((levels > 0)); do
cd .. || break
let “levels–”
done
}
with this you’ll do “.. 3” and it will go back three levels and you can use any number.
A friend and myself have been arguing about an issue similar to this one! Now I know that I was right. lol! Thanks for the information you posted.
Regarding changing up directory levels in Linux, here’s the method I use all the time. First, I define a shell script called upl somewhere on my path:
#!/bin/bash
if [ $1 ]
then
steps=$1
else
steps=1
fi
while [ $steps -gt 0 ]
do
cd ..
(( steps = steps – 1 ))
done
pwd
Then, I add the following line to my .bashrc:
alias up=”source upl”
Then, wherever I am, it’s simply a metter of typing “up” to just go up one level, or “up ” to step up of levels. So if I’m 8 levels doen in a massive source tree, typing “up 8” will immediatley jump up 8 levels, and print the new directory where I am. In this way, I can roughly guess how many levels I need to step up, and fine tune if afterwards, if required.
While extremely noddy, this simple script saves so much hassle ,and I really think something like it should be standard in the Linux command shell.
Beware that this forum is apparently susceptible to browser security hacks. In my previous post, I used angle brackets (less than and greater than symbols) to outline the parameter to my up command, but your site interpreted these as HTML tags and they did not appear. So my text should have read something like “up number to step up number of levels”, where number was encased in these brackets.
Since the site seems to interpret raw text as HTML, I can imagine that it would be possible to embed all sorts of nasties in here. In my opinion, anything entered on forums should be interpreted as raw text and displayed as such.
When i m trying jump to directories above using alias i am getting the following error:
“-bash: alias: …..: not found”
“-bash: alias: cd: not found”
Could some one suggest me? Thanks.
Rather than re-logging in after creating the function in .bashrc it’s much easier to just enter ‘. .bashrc’ (the dot is short for the “source” command).
In recent bash versions, there are
shopt -s autocd # will automatically cd if only a dir is given
and
shopt -s cdable_vars # will let you cd into a variable
This will enable:
doc@desktop:~$ shopt -s autocd cdable_vars ; foo=”/tmp”; $foo
cd /tmp
So you can just type your $var and will be taken to the directory $var represents.
Useful for stuff like $gitrepo, $rpmbuild, $sources and so on.
Remember to use lowercase variable names to avoid accidential overriding of environment variables.
Superb tricks. You are the Linux guru.
what’s the usage of hack #5? thack u!
Here is a slight improvement I have found:
Usually, when you go back one directory with cd .., you end up going forward one directory after. To make this work, you have to use functions rather than aliases, so instead of:
alias ..=”cd ../”
alias ..2=”cd ../../”
you can use:
..()
{
cd ../$@
}
..2()
{
cd ../../$@
}
However, after using this, it quickly becomes apparent that you are missing command completion for this function, making it far less useful than it could be. Thus, I went back and added my own bash completion functions for this function, which can be pasted into your ~/.bashrc or any file (e.g. ~/.bash_completion) that is called from your ~/.bashrc if you wish to avoid clutter. Here is the completion code:
_..()
{
local cur=../${COMP_WORDS[COMP_CWORD]}
COMPREPLY=( $(compgen -d — $cur) )
local i=${#COMPREPLY[*]}
while [ $((–i)) -ge 0 ]; do
COMPREPLY[$i]=$(echo ${COMPREPLY[$i]} | sed -r ‘s/(\.\.\/)*//’)
done
}
complete -F _.. -o nospace -S / ..
_..2()
{
local cur=../../${COMP_WORDS[COMP_CWORD]}
COMPREPLY=( $(compgen -d — $cur) )
local i=${#COMPREPLY[*]}
while [ $((–i)) -ge 0 ]; do
COMPREPLY[$i]=$(echo ${COMPREPLY[$i]} | sed -r ‘s/(\.\.\/)*//’)
done
}
complete -F _..2 -o nospace -S / ..2
You can go to your previous directory, not one directory up using `cd -`
For example, if you are in /var/
cd ~
would take to your home directory. So go to your previous directory use cd –
then directory will change to /var/.
Bash variable in which this value stored is OLDPWD
echo $OLDPWD
This variable will be empty if you did not change your directory after opening a new shell.
what is the use of directory stack. and where it is necessary ??
I have found that the use of Directory Bookmarks (see here) to be something I depend upon daily for my development work. It adds quite a bit of power to command line navigation.
Ira
Why would I want to create a directory stack ? What is its practical purpose ?
Whats the practical use/purpose of directory stack?
The “shopt -s cdspell” not working.
Getting the error “/etc/mall: No such file or directory” again.
[Tested in: Ubuntu 14.04, GNU bash, version 4.3.11]
Its help me lot,Thank U 🙂
Good list here.
Especially see acd_func.sh which is not covered in this article.
The “shopt -s cdspell” not working.
Tried it on RHEL
shopt -s cdspell: Does it work only up to one spelling correction ?