How to use cd - with pushd/popd?

The pushd and popd commands are used in conjunction with cd - to manage a stack of directories, allowing you to navigate back and forth between multiple directories easily.

How to Use pushd and popd:

  1. Using pushd to Navigate:
    When you use pushd, it saves the current directory on a stack and then changes to the specified directory.

    pushd /path/to/directory1
  2. Navigate to another directory:
    You can use pushd again to navigate to another directory, which will save the previous directory on the stack.

    pushd /path/to/directory2
  3. Using popd to Return:
    To return to the previous directory saved on the stack, use popd.

    popd

    This will take you back to /path/to/directory1.

  4. Using cd -:
    You can also use cd - to switch back to the last directory you were in, but it won't affect the stack created by pushd and popd. If you want to return to the last directory you were in before the current one, you can use:

    cd -

Example Workflow:

# Start in /home/user
pushd /path/to/directory1  # Stack: /home/user -> /path/to/directory1
pushd /path/to/directory2  # Stack: /path/to/directory1 -> /path/to/directory2

# Now in /path/to/directory2
popd                       # Returns to /path/to/directory1
# Now in /path/to/directory1

cd -                       # Returns to /home/user
# Now in /home/user

Summary:

  • Use pushd to save the current directory and navigate to a new one.
  • Use popd to return to the last directory saved on the stack.
  • Use cd - to quickly switch back to the last directory you were in, but it does not interact with the stack.

0 Comments

no data
Be the first to share your comment!