TIP Tricks with cd

From Gentoo Linux Wiki

Jump to: navigation, search
This article is part of the Tips & Tricks series.
Terminals / Shells Network X Window System Portage System Filesystems Kernel Other

Contents

[edit] Ways to return to your home directory:

$ cd ~
$ cd ~/
$ cd
$ cd $HOME

If you are just showing off, you could also type anything after cd that has no value. It would be the same as typing cd by itself. Try these, they'll take you home too. (if $me is not defined)

cd --
cd $me
cd $blahblahblah

[edit] Change to the last created directory

[ESC]. returns last entered argument (that's the escape key, followed by the dot key)

$ mkdir /foo/bar
$ cd [ESC].
$ pwd

You can also use !$ to return the last argument

$ ls -d /foo /foo/bar
$ cd !$
$ pwd
/foo/bar

Or you can use !:<number> to refer to a specific argument

$ mkdir /foo/bar/beer /foo/bar/shot /foo/bar/wine
$ cd !:2
$ pwd
/foo/bar/shot

[edit] To go to another users home directory type:

$ cd ~username

[edit] To return to the last directory you were in:

$ cd -

[edit] To use directory stacks:

$ pwd
/home
$ pushd /etc
/etc /home
$ pwd
/etc
$ popd
/home
$ pwd
/home
$

[edit] Using parent directories to move about

The simplest use is to move to the parent (next one up) directory.

cd ..

But they can be chained together like any other directory, and it's quicker than stepping up one directory at a time. This example goes up three levels.

cd ../../..

It can be a quick way to go `sideways` in the directory structure. Say you are in /etc/init.d and want to change to /etc/conf.d, you could do it like this:

$ cd ..
$ cd conf.d

or you could simply type

$ cd ../conf.d

These examples are rather simplistic. Really useful when you are several directories deep and don't want to start back at the root directory.

[edit] Moving "Sideways" along the filesystem

If you find yourself in somewhere like /usr/appone/long/path/you/do/not/want/to/type/each/time, and you want to move into /usr/apptwo/long/path/you/do/not/want/to/type/each/time, you can substitute appone for apptwo in your current directory variable.

Your current directory is stored in $PWD variable - for this example, you can use the following to make the substitution, which replaces appone for apptwo in the $PWD variable.

cd ${PWD/appone/apptwo}

[edit] Use the TAB key

The Tab key can be a real time and frustration saver if you use cd with long pathnames. I suppose its exact behavior depends on which shell you are using.

If you add the following line to your .bashrc, TAB completion will only complete on directories when used with cd:

complete -d cd

[edit] Enable cdspell

Enable cdspell in your .bashrc

shopt -s cdspell

This will fix minor typos, for cd, and only for cd Try:

$ cd /etc/initd
$ pwd
/etc/init.d
$ cd /var/lgo
$ pwd
/var/log

[edit] See Also

Original Forum Post

Personal tools
In other languages