DEV Community

Cover image for TIL: you can use `cd ~number` to navigate back to previously visited directories
👨‍💻Ioannis Diamantidis
👨‍💻Ioannis Diamantidis

Posted on • Originally published at diamantidis.github.io

TIL: you can use `cd ~number` to navigate back to previously visited directories

If you are a heavy user of the command line (as I am 🤓), there is a high chance that you use the command cd quite often to navigate back and forth to different directories.

Besides the popular cd <dir>, cd has some more capabilities that are not so widely known and can make the navigation between different directories much more efficient.

Let's say we have the following directory structure and we have to navigate through those folders.

parent
├── child1
│   └── grandchild1
└── child2
    └── grandchild2
Enter fullscreen mode Exit fullscreen mode

For example, we have to run the following commands:

cd child1
cd grandchild1
cd ../../child2
cd grandchild2
Enter fullscreen mode Exit fullscreen mode

Did you know that you can use cd ~2 to navigate back to ~/parent/child1/grandchild1?

Let me try to explain how this is working.
All the directories that we have visited are stored in a stack. To display this stack, we can use the command dirs -v, which will output something like the following:

0   ~/parent/child2/grandchild2
1   ~/parent/child2
2   ~/parent/child1/grandchild1
3   ~/parent/child1
4   ~/parent
Enter fullscreen mode Exit fullscreen mode

You can now use the number on the left of the directory to navigate through the stack. In our case, we are using cd ~2 to navigate to the item in position 2.

Isn't that cool? Especially compared to the alternative(cd ../../child1/grandchild1)? 😎


➡️ This post was originally published on my blog.

Top comments (3)

Collapse
 
moopet profile image
Ben Sinclair

I didn't know this. I like this but find it takes a little thinking about to do.
It'd be neat to use something like fzf to fuzzy match through the stack, maybe?

I'm a fan of using cd - to swap between he current and previous directory.

Collapse
 
djsullenbarger profile image
David Sullenbarger

TIL: This from you, thanks!

also: "cd .." or "cd.." (system dependent) backs up one directory

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

Unfortunately, this isn't working on Ubuntu 20.04 LTS with Bash.