While everyone familiar with a shell know about the command
there are a few tips you should know.
Moving to your $HOME directory
$ pwd /tmp $ cd $ pwd /home/solene
cd without argument will change your current directory to
Moving into someone $HOME directory
While this should fail most of the time because people shouldn’t allow anyone to visit their $HOME, there are use case it can be used though.
$ cd ~user1 $ pwd /home/user1 $ cd ~solene $ pwd /home/solene
~user as a parameter will move to that user $HOME directory,
cd ~youruser have the same result.
Moving to previous directory
This is a very useful command which allow going back and forth between two directories.
$ pwd /home/solene $ cd /tmp $ pwd /tmp $ cd - /home/solene $ pwd /home/solene
When you use
cd - the command will move to the previous directory
in which you were. There are two special variables in your shell:
OLDPWD, when you move somewhere,
OLDPWD will hold
your current location before moving and then
PWD hold the new
path. When you use
cd - the two variables get exchanged, this
mean you can only jump from two paths using
cd - multiple times.
Please note that when using
cd - your new location is displayed.
Changing directory by modifying current PWD
thfr@ showed me a cd feature I never heard about, and it’s the perfect place to write about it. Note that this work in ksh and zsh but is reported to not work in bash.
One example will explain better than any text.
$ pwd /tmp/pobj/foobar-1.2.0/work $ cd 1.2.0 2.4.0 /tmp/pobj/foobar-2.4.0/work
cd to replace first parameter pattern by the second
parameter in the current
PWD and then cd into it.
$ pwd /home/solene $ cd solene user1 /home/user1
This could be done in a bloated way with the following command:
$ cd $(echo $PWD | sed "s/solene/user1/")
I learned it a few minutes ago but I see a lot of uses cases where I could use it.
Moving into the current directory after removal
In some specific case, like having your shell into a directory that existed but was deleted and removed (this happens often when you working into compilation directories).
A simple trick is to tell
cd to go to the current location.
$ cd .
$ cd $PWD
cd will go into the same path and you can start hacking
again in that directory.