Wednesday, 31 May 2017

How to Use dirs, pushd and popd to manipulate directory stack


You can use directory stack to push directories into it and later pop directory
from the stack. Following three commands are used in this example.

o dirs: Display the directory stack
o pushd: Push directory into the stack
o popd: Pop directory from the stack and cd to it
Dirs will always print the current directory followed by the content of the
stack. Even when the directory stack is empty, dirs command will still print
only the current directory as shown below.
# popd
-bash: popd: directory stack empty
# dirs
~
# pwd
/home/ramesh
How to use pushd and popd? Let us first create some temporary directories
and push them to the directory stack as shown below.
#
#
#
#
mkdir
mkdir
mkdir
mkdir
/tmp/dir1
/tmp/dir2
/tmp/dir3
/tmp/dir4
# cd /tmp/dir1
# pushd .
# cd /tmp/dir2
# pushd .
# cd /tmp/dir3
# pushd .
# cd /tmp/dir4
# pushd .

# dirs
/tmp/dir4 /tmp/dir4 /tmp/dir3 /tmp/dir2 /tmp/dir1
[Note: The first directory (/tmp/dir4) of the dir
command output is always the current directory and not
the content from the stack.]
At this stage, the directory stack contains the following directories:
/tmp/dir4
/tmp/dir3
/tmp/dir2
/tmp/dir1
The last directory that was pushed to the stack will be at the top. When you
perform popd, it will cd to the top directory entry in the stack and remove it
from the stack. As shown above, the last directory that was pushed into the
stack is /tmp/dir4. So, when we do a popd, it will cd to the /tmp/dir4 and
remove it from the directory stack as shown below.
# popd
# pwd
/tmp/dir4
[Note: After the above popd, directory Stack Contains:
/tmp/dir3
/tmp/dir2
/tmp/dir1]
# popd
# pwd
/tmp/dir3
[Note: After the above popd, directory Stack Contains:
/tmp/dir2
/tmp/dir1]
# popd
16

# pwd
/tmp/dir2
[Note: After the above popd, directory Stack Contains:
/tmp/dir1]
# popd
# pwd
/tmp/dir1
[Note: After the above popd, directory Stack is empty!]
# popd
-bash: popd: directory stack empty

No comments:

Post a Comment

What is PS2 - Continuation Interactive Prompt in Linux

A very long command can be broken down to multiple lines by giving \ at the end of the line. The default interactive prompt for a multi-lin...