Project 14. Navigate the File System"How do I move around the file system and then get back to where I was ten minutes ago?" This project is useful if you have a tendency to hop from one directory to another and forget where you came from. It covers the commands pushd, popd, and dirs. Pushing and PoppingBash implements a directory stack. You push directories onto the stack in the order A, B, C and then pop them off the stack in the reverse order C, B, A. It's like leaving a trail of breadcrumbs so you can retrace your steps. Instead of using the cd command, use pushd to change to a new directory and stack the old one; then use popd to return to a previous directory. Use the dirs command at any time to display the directory stack. All three are Bash built-in commands. As an example, let's start in our home directory. $ pwd /Users/saruman Next, we move to the directory /etc/httpd, stacking our home directory. The pushd command also echoes the current directory stack. $ pushd /etc/httpd /etc/httpd ~ Then we move to the directory /var/log and from there to /Volumes. $ pushd /var/log /var/log /etc/httpd ~ $ pushd /Volumes /Volumes /var/log /etc/httpd ~ Use the dirs command to display the current directory stack, which should trace back to where we started. The verbose option -v tells dirs to list the directory stack line by line, numbering each entry. $ dirs -v 0 /Volumes 1 /var/log 2 /etc/httpd 3 ~ Tip
Now use popd to retrace our steps. The popd command also echoes the current directory stack. $ popd /var/log /etc/httpd ~ $ pwd /var/log $ popd /etc/httpd ~ $ pwd /etc/httpd $ popd ~ Note
Manipulate the Directory StackThe directory stack is a Bash array variable and can, therefore, be read and written just like any other. You may use the pushd and popd commands to manipulate the stack and jump directly to any directory on the stack. Given the following stack $ dirs -v 0 / 1 /usr/local/bin 2 /etc/httpd 3 /var/log we can jump straight to the directory /etc/httpd (enTRy number 2), rotating the stack appropriately, by using $ pushd +2 /etc/httpd /var/log / /usr/local/bin $ pwd /etc/httpd $ dirs -v 0 /etc/httpd 1 /var/log 2 / 3 /usr/local/bin Tip
Learn More
Mimic a Tcsh Shell Feature in BashThe Tcsh shell also has built-in pushd, popd, and dirs commands. These commands have a few extra features, such as saving the directory stack from one shell session to the next and a silent mode in which the directory stack is not echoed back in the command line each time pushd and popd are used. Tip
If you'd like to silence the pushd and popd commands in Bash, you can do so easily. Just define a couple of aliases that discard the standard out generated by pushd and popd. $ alias pud='pushd >/dev/null' $ alias pod='popd >/dev/null' Learn More
Errors will still show because they are sent to standard error. Let's test the aliases. $ dirs /Users/saruman $ pud /etc/httpd $ pud /var/log $ dirs /var/log /etc/httpd /Users/saruman $ pod $ pod $ dirs /Users/saruman |