18. Bash Shell - Directory Stack Builtins
Contents
With a directory stack, we can push the directories we visit sequentially into the directory stack, and when we’ve done a series of operations, we can go all the way back to the origin based on the record of the directory stack.
Directory Stack Commands
The directory stack provides us with three available commands.
dirs
Displays all directories recorded in the directory stack:
|
|
pushd
Records the specified directory to the directory stack and switches the working directory to the recorded directory:
|
|
popd
Remove the last directory recorded in the directory stack and switch the working directory to the removed directory:
|
|
Preparing Directories
Let’s prepare some directories for demonstration:
|
|
Now that we have some nested directories, we can begin to demonstrate. The directory stack can store any directory we push into, and the nested directory is used here just for ease of operation.
Use of Commands
Adding Directories
Let’s adding directories to directory stack:
|
|
Show Recorded Directories
By Default
Use dirs to print the recorded directories:
|
|
With User Home Directory Name
Use dirs -l to print the recorded directories with user home directory’s name instead of a tilde:
|
|
Line by Line
Use dirs -p to print the recorded directories line by line:
|
|
Line by Line With Their Indexes
Use dirs -v to print the recorded directories line by line with their indexes:
|
|
First Recorded Directory
Use dirs -0 to print the first recorded directory:
|
|
Last Recorded Directory
Use dirs +0 to print the last recorded directory:
|
|
Use Recorded Directories
Use From right
Use pushd -0 to change to the rightmost directory and use it as a working directory:
|
|
Use From left
Use pushd +1 to change to the directory before the leftmost one and use it as a working directory:
|
|
Remove Recorded Directories
Remove From right
Use popd -0 to remove the rightmost directory:
|
|
Remove From left
Use popd +0 to remove the leftmost directory and use the previous directory as a working directory:
|
|
References 6.8.1 Directory Stack Builtins
Author Dong Chen
LastMod Tue Feb 19 2019