Posted in bash

Changing directories

Everyone knows the command cd – everyone uses it several times a day. (OK – not everyone, but every Linux user.) Most of us know, that we can change back to the last directory with

$ cd -

E.g.:

$ pwd
/home/maker/docs/sensors
$ cd /opt/sensors/bmp280
$ pwd
/opt/sensors/bmp280
$ cd -
$ pwd
/home/maker/docs/sensors

But what if you cd in your project directory and then need to change back into your docs directory? You have to type the whole path. Or do you?

This is where the shell builtins pushd and popd come into play. pushd puts the actual directory onto the directory stack and changes into the directory submitted as parameter. popd takes the last directory from the stack and changes into it.

$ pwd
/home/maker/docs/sensors
$ pushd /opt/sensors/bmp280
/opt/sensors/bmp280 ~/docs/sensors
$ pwd
/opt/sensors/bmp280
$ cd programs/readsensor
$ pwd
/opt/sensors/bmp280/readsensor
$ popd
~/docs/sensors
$ pwd
/home/maker/docs/sensors

You are not limited to one entry. You can pushd into the project directory, then pushd into a temp directory, pushd into a log directory, and switch back stepwise.

The command dirs shows the actual directory stack:

$ dirs
/opt/sensors/bmp280 ~/docs/sensors /opt/sensors/logs

There are parameters to these commands to manipulate the directory stack; just have a look into the man page:

$ man bash
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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