Google Analytics

Search

To search for specific articles you can use advanced Google features. Go to www.google.com and enter "site:darrellgrainger.blogspot.com" before your search terms, e.g.

site:darrellgrainger.blogspot.com CSS selectors

will search for "CSS selectors" but only on my site.


Saturday, July 12, 2014

DIRSTACK

I was recently poking around on my Terminal (Mac OS X) and I noticed one of the environment variables was:
DIRSTACK=()
So I checked the man page for the bash shell to see what I could find about it:
man bash
Reading the man page I find DIRSTACK is an array relating to popd, pushd and dirs. Rather than using cd to change to a directory I can use pushd. For example:
pushd ~/Downloads
This will change directory to ~/Downloads plus it will add the directory to the DIRSTACK array. I can add some more to the DIRSTACK using:
pushd ~/Documents
pushd /Volumes
Now if I issue a dirs I will see:
/Volumes ~/Documents ~/Downloads
If you search for popd, pushd and dirs on the bash man page you will find all the settings for these builtin commands:
dirs [-clpv] [+n] [-n]
+n display the nth entry from the left, e.g. +2 will display the entry in position 2, this is zero-indexed
-n displays the nth entry from the right, just like the +n this is zero-indexed, e.g. -0 is the first entry
-c clears the DIRSTACK
-l displays a longer list, e.g. ~ gets expanded to the full directory name /Users/darrell
-p display one entry per line
-v display one entry per line with a number at the start of each line

You might thing the -v option is just line numbers but they are more than that. The numbers are directly related to the -n and +n option. Additionally, I can refer to specific entries in the list using ~n. For example, if the dirs -v displays:
 0  ~/Public
 1  ~/Downloads
 2  ~/Documents
 3  ~
then ls -l ~2 will be the same as ls -l ~/Documents. I can also use the tilde notation for popping elements off the stack as well. The next command, popd, has the following format:
popd [-n] [+n] [-n]
-n is literally -n, when you normally popd it will change to the directory you pop, -n will suppress this
+n removes n entries from the left, e.g. +2 will remove from third element from left (zero-indexed)
-n removes n entries from the right, e.g. -1 will pick the second element from right

The pushd commands looks similar:
pushd [-n] [dir]
pushd [-n] [+n] [-n]
-n is literally -n, and like popd it adds to the stack but does not cd to the new directory.
[dir] will push [dir] on the DIRSTACK then cd [dir]
+n will rotate the stack so the nth directory from the left is at the top
-n will roate the stack so the nth directory from the right is at the top

.

No comments: