Use Bash Shell History to Combine Paths from cd Commands

This blog post explains how you can use Bash shell command history to combine sequences of cd commands that take you to a deep path.

I often use multiple cd commands to navigate to a directory.

cd /mnt/c/temp/sln
cd HeadlessArchitect
cd HeadlessArchitect.Website

If I want to go back one cd, I can use issue the cd – command. Sometimes I want to go back several directories. For example, after the following commands that take the shell to /tmp/models, I want to get back to /mnt/c/temp/sln/HeadlessArchitect/HeadlessArchitect.Website.

cd /tmp
cd models

The pushd and popd commands do not seem to work how I would like. To assist with navigating paths, I create the cds alias that greps cd commands (well, anything that contains the text “cd”) from the shell command history.

alias cds='history | grep cd'

This belongs in shell initialization as described in the following blog post.

While looking at shell configuration, you may want to make it easier to navigate to directories that you use frequently by setting the CDPATH environment variable, which contains a list of directories that the cd command checks for relative paths.

I use the exclamation point to re-issue numbered commands from the history. Line numbers will vary.

cds
!3
!4
!5

Actually, I use a semicolon to combine these commands into a new command that appears in the history, and then I get a new command that combines them.

!3 ; !4 ; !5
cd /tmp
cd models
cds
!10

I recommend that you clean your history at login as described in the following blog post, which re-orders the history to move least used commands to the past in the history.

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: