If you’re like me, you spend a lot of time jumping from project to project in a Linux shell. I find that I have to switch back and forth between directories. The bash shell has commands to maintain a stack of directories. I’ve written some functions that use these utilities to make directory navigation easier. I’ve found these functions very useful, and perhaps you will too. Let’s see them in action first with some examples, and then look at the code:
In this first snippet, I start working in the Documents/Training/qt/ch1 directory:
1 2 3 4 5 6 7 | |
Now let’s say I have to work in the TaskForest lib directory for a while:
1 2 3 4 5 6 7 8 | |
Now my work gets preempted because I have to work in the ‘rates’ directory:
1 2 3 4 5 6 7 8 | |
After finishing my work in the rates directory, I want to get back to what I was doing, but I can’t remember exactly what where I was before I got interrupted. So I enter the ‘d’ command which displays the stack of directories. Every time I used the ‘cd’ command, the system pushed the directory I was in onto a stack. The ‘d’ command displays the stack and prompts me for an entry. If I enter a number, it pushes the directory that’s at that position in the stack to the top, and enters that directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
You can see that when I entered ‘2’ above, the ‘d’ command pushed the ’~/Documents/Training/qt/ch1’ directory to the top of the stack and entered that directory. You can see the modified directory stack above. I entered ‘d’ again to view the directory stack, but this time entered ‘q’ to do nothing.
I’ve also created the ‘p’ command, which pops the current directory off the top of the stack and enters the directory that was under it.
1 2 3 4 5 6 7 8 9 10 | |
Now let’s have a look at the code that makes this work. You can copy and paste this code directly into your .bashrc file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | |