Backtracking with bash
I was working with linux quite a bit today, and frequently changing between directories, when I wondered if there was a way to go back to the directory I was in previously.
Turns out there is a way:
cd ~-So if I was doing something like this:
[pete@bigred /]$ cd /etc [pete@bigred etc]$ cd /usr/local [pete@bigred local]$ cd ~- [pete@bigred etc]$ pwd /etcIf you want to create a command so you don't have to type
~-you can create an alias:
alias cdb='cd ~-'This
~-thing works great if you only need to go back one directory, but what if you wanted to go back two directories. Continuing the last code sample:
[pete@bigred etc]$ cd ~- [pete@bigred local]$ cd ~- [pete@bigred etc]$ pwd /etcWe are back to
/our starting point. What I want is something that keeps a history of the directories I've been to.
It turns out that the Bash (the "Bourne again shell") has a directory stack builtin. Three command line tools for manipulating the stack are avaliable
pushd a directory onto the directory stack, we can retrieve the top of the stack using
dirs +1. I tried setting up some aliases to get it to work the way I wanted:
alias cdd='pushd' alias cdb='cd `dirs +1`'Those worked a bit, but I ran into a lot of problems, especially when in the home directory. Also when you run pushd, popd, or dirs it always prints the contents of the stack, I don't know how to suppress that. So I figured I would post it here, and see if anyone can come up with a solution, or if anyone knows of a better way of going about this.
Isn't it funny how software developers will spend hours of time trying to save a few seconds of their future time.
Update: I did find a workaround here.
Like this? Follow me ↯Tweet Follow @pfreitag
Backtracking with bash was first published on April 01, 2003.
If you like reading about bash, or linux then you might also like:
- Creating a Symbolic Link with ln -s What Comes First?
- Bash Loop To Wait for Server to Start
- Counting IP Addresses in a Log File
- Recursively Counting files by Extension on Mac or Linux
- Passing Environment Variables to Sudo Command
- Difference between cd - vs cd ~-
- The 15 Essential UNIX commands
- Linux and OS X Shell Commands
Want Security Advisories via Email?
Advisory Week is a new weekly email containing security advisories published by major software vendors (Adobe, Apple, Microsoft, etc).