How to change directory quickly with pushd
pushd
pushd changes directory similar to cd, but it also pushes the directory onto a navigation stack. Then you can use the stack to change to any previous directory.
pushd ~/Documents/projects/python_projects/my_project
To show the directory stack:
dirs -v
Example output
0 ~/Documents/projects/ios_projects
1 ~/Documents/Beepscore/Eng/programming_info/HardwareInfo/raspberry_pi_info
2 ~/Documents/projects/python_projects/my_project
3 ~/dotfiles
4 ~
You can change directory by referencing its number on the current stack:
pushd -2
shell script
I wrote a script file to push several directory names onto the stack. Then to run the script at start, in macOS iTerm / Preferences / Profiles / Command / Login Shell / Send text at start, enter
source <script name>
For example
source ~/bin/terminal_start.zsh
example shell script
#!/usr/bin/env zsh
# run as "source terminal_start.zsh" so that commands will have effect in outer shell outside of subshell.
# https://stackoverflow.com/questions/255414/why-doesnt-cd-work-in-a-shell-script
# shellcheck suggests add || return in case pushd fails
printf "%s\n" ""
printf "%s\n" "pushd push onto directory stack and change directory"
pushd ~/dotfiles || return
pushd ~/Documents/projects/python_projects/my_project || return
pushd ~/Documents/Beepscore/Eng/programming_info/HardwareInfo/raspberry_pi_info || return
pushd ~/Documents/projects/ios_projects || return
# prefer printf over echo
# https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo/65819#65819
# https://unix.stackexchange.com/questions/58310/difference-between-printf-and-echo-in-bash?noredirect=1&lq=1
printf "%s\n" ""
printf "%s\n" "dirs -v show directory stack"
dirs -v
printf "%s\n" ""
printf "%s\n" "pushd toggle between 2 most recent, similar to cd -. Note this changes stack numbering."
printf "%s\n" "pushd -n navigate to directory number n. Note this changes stack numbering."
script disadvantages
The startup script requires maintenance. If you start working on a new project using new directories, you must manually edit the script.
how to install
pushd is a standard command, no need to install a package.
References
Use 'pushd' and 'popd' for Efficient Filesystem Navigation in Linux
https://www.tecmint.com/pushd-and-popd-linux-filesystem-navigation/
pushd, popd vs cd, cd- in bash and zsh
https://unix.stackexchange.com/questions/272965/pushd-popd-vs-cd-cd-in-bash-and-zsh