How do I use pushd and popd commands?
What are the practical uses of both
popdwhen there is an advantage of using these two commands over
EDIT: I'm looking for some practical examples of uses for both of these commands or reasons for keeping stack with directories (when you have tab completion,
cd -, aliases for shortening
cd .., etc.).
start up with the following directories:
$ ls dir1 dir2 dir3
pushd to dir1
$ pushd dir1 ~/somedir/dir1 ~/somedir $ dirs ~/somedir/dir1 ~/somedir
dirscommand confirms that we have 2 directories on the stack now.
dir1and the original dir,
somedir. NOTE: Our "current" directory is
pushd to ../dir3 (because we're inside
$ pushd ../dir3 ~/somedir/dir3 ~/somedir/dir1 ~/somedir $ dirs ~/somedir/dir3 ~/somedir/dir1 ~/somedir $ pwd /home/saml/somedir/dir3
dirsshows we have 3 directories in the stack now.
somedir. Notice the direction. Every new directory is getting added to the left. When we start popping directories off, they'll come from the left as well.
manually change directories to
$ cd ../dir2 $ pwd /home/saml/somedir/dir2 $ dirs ~/somedir/dir2 ~/somedir/dir1 ~/somedir
Now start popping directories
$ popd ~/somedir/dir1 ~/somedir $ pwd /home/saml/somedir/dir1
Notice we popped back to
$ popd ~/somedir $ pwd /home/saml/somedir
And we're back where we started,
Might get a little confusing, but the head of the stack is the directory that you're currently in. Hence when we get back to
somedir, even though
$ dirs ~/somedir
Our stack is in fact empty.
$ popd bash: popd: directory stack empty
Thanks, I totally understand the concept of stack and how this commands work. However, I'm looking for some practical reasons for keeping stack with directories (when you have tab completion, `cd -`, aliases for shortening `cd ..`, etc.).
I often use `pushd` & `popd` in scripts b/c they save me from having to remember where I was coming from, I can always just `popd` to get back from where I came. I usually do `popd >/dev/null 2>&1` to make it silent. I use cd- everyday in my shell. There are some other time saving tips in this article as well: http://www.thegeekstuff.com/2008/10/6-awesome-linux-cd-command-hacks-productivity-tip3-for-geeks/.
Take a look at `$CDPATH`. It's pretty powerful if you're looking for more efficient ways to get around via cd.
@slm, is there any advantage to using `popd >/dev/null 2>&1` in a script rather than `cd - >/dev/null 2>&1`?
@Garrett @slm since `cd -` only tracks the last directory, i imagine it would be possible to have issues if you call a function which also changes directory internally. in that case, the function would end up resetting - to your current directory, not the directory you want to pop back to. pushd/popd is the safest method. Note: i haven't tested my theory.