Bash primitive, outdated cd command that doe not maintain history of visited directories. That deficiency created cottage industry of enhancement that try to alleviate this shortcoming with more or less success.
There is one approach to use the set of all files like locate command in Unix or famous NCD command in DOS (which provides visual navigation over the current directory tree.
the other is to use regular expressions to shorten complex path to few letters. Alias system also can be used.
Few people know that bash allow to use variable is cd command without leading $ if you set shopt -s cdable_vars
w="/srv/www/public_html' cd wcdable_vars is also nice
popd/pushd/dirs troika of bash commands bark to the wrong tree as navigation is never stack based activity, but can be adapted to be more useful. If you alias cd to pushd you will have the stack of recently visited directories handy.
|
Switchboard | ||||
Latest | |||||
Past week | |||||
Past month |
Feb 04, 2017 | hints.macworld.com
The variable CDPATH defines the search path for the directory containing directories. So it served much like "directories home". The dangers are in creating too complex CDPATH. Often a single directory works best. For example export CDPATH = /srv/www/public_html . Now, instead of typing cd /srv/www/public_html/CSS I can simply type: cd CSS
Use CDPATH to access frequent directories in bash
Mar 21, '05 10:01:00AM Contributed by: jonbaumanI often find myself wanting to cd to the various directories beneath my home directory (i.e. ~/Library, ~/Music, etc.), but being lazy, I find it painful to have to type the ~/ if I'm not in my home directory already. Enter CDPATH , as desribed in man bash ):
The search path for the cd command. This is a colon-separated list of directories in which the shell looks for destination directories specified by the cd command. A sample value is ".:~:/usr".Personally, I use the following command (either on the command line for use in just that session, or in .bash_profile for permanent use):This way, no matter where I am in the directory tree, I can just cd dirname , and it will take me to the directory that is a subdirectory of any of the ones in the list. For example:CDPATH=".:~:~/Library"
[ robg adds: No, this isn't some deeply buried treasure of OS X, but I'd never heard of the CDPATH variable, so I'm assuming it will be of interest to some other readers as well.]$ cd $ cd Documents /Users/baumanj/Documents $ cd Pictures /Users/username/Pictures $ cd Preferences /Users/username/Library/Preferences etc...
cdable_vars is also nice
Check out the bash command shopt -s cdable_vars
Authored by: clh on Mar 21, '05 08:16:26PMFrom the man bash page:
cdable_varsWith this set, if I give the following bash command:If set, an argument to the cd builtin command that is not a directory is assumed to be the name of a variable whose value is the directory to change to.
export d="/Users/chap/Desktop"
I can then simply type
cd d
to change to my Desktop directory.
I put the shopt command and the various export commands in my .bashrc file.
Stack Overflow
Is there any directory bookmarking utility for bash to allow move around faster on the command line?
UPDATE
Thanks guys for the feedback however I created my own simple shell script (feel free to modify/expand it)
function cdb() { USAGE="Usage: cdb [-c|-g|-d|-l] [bookmark]" ; if [ ! -e ~/.cd_bookmarks ] ; then mkdir ~/.cd_bookmarks fi case $1 in # create bookmark -c) shift if [ ! -f ~/.cd_bookmarks/$1 ] ; then echo "cd `pwd`" > ~/.cd_bookmarks/"$1" ; else echo "Try again! Looks like there is already a bookmark '$1'" fi ;; # goto bookmark -g) shift if [ -f ~/.cd_bookmarks/$1 ] ; then source ~/.cd_bookmarks/"$1" else echo "Mmm...looks like your bookmark has spontaneously combusted. What I mean to say is that your bookmark does not exist." ; fi ;; # delete bookmark -d) shift if [ -f ~/.cd_bookmarks/$1 ] ; then rm ~/.cd_bookmarks/"$1" ; else echo "Oops, forgot to specify the bookmark" ; fi ;; # list bookmarks -l) shift ls -l ~/.cd_bookmarks/ ; ;; *) echo "$USAGE" ; ;; esac }
INSTALL
1./ create a file ~/.cdb and copy the above script into it.
2./ in your ~/.bashrc add the following
if [ -f ~/.cdb ]; then source ~/.cdb fi
3./ restart your bash session
USAGE
1./ to create a bookmark
$cd my_project $cdb -c project1
2./ to goto a bookmark
$cdb -g project1
3./ to list bookmarks
$cdb -l
4./ to delete a bookmark
$cdb -d project1
5./ where are all my bookmarks stored?
asked Sep 10 '11 at 20:35$cd ~/.cd_bookmarks
Take a look at autojump: github.com/joelthelion/autojump/wiki arnaud576875 Sep 10 '11 at 20:36 Why is the question and your script bash specific? You should try avoiding bash scripts. Write shell scripts instead. Jens Sep 11 '11 at 18:02 @Jens i used this book to do what i wanted to do. getmizanur Sep 12 '11 at 5:38 This one's quite good, too. jeroenjanssens.com/2013/08/16/ It even has auto-complete. mjswensen Mar 15 '16 at 22:44 active oldest votes
Also, have a look at CDPATH A colon-separated list of search paths available to the cd command, similar in function to the $PATH variable for binaries. The $CDPATH variable may be set in the local ~/.bashrc file.
ash$ cd bash-doc bash: cd: bash-doc: No such file or directory bash$ CDPATH=/usr/share/doc bash$ cd bash-doc /usr/share/doc/bash-doc bash$ echo $PWD /usr/share/doc/bash-doc
and
cd -
It's the command-line equivalent of the back button (takes you to the previous directory you were in).
edited Sep 10 '11 at 20:53 answered Sep 10 '11 at 20:47 Fredrik Pihl
28.6k14378
3 cheers for that. getmizanur Sep 11 '11 at 6:26 I prefer this solution since I have well organized directory structure. MeanEYE Feb 2 '15 at 12:26
In bash script/command,
you can usepushd
andpopd
Save and then change the current directory. With no arguments, pushd exchanges the top two directories.
Usage
cd /abc pushd /xxx <-- save /abc to environment variables and cd to /xxx pushd /zzz pushd +1 <-- cd /xxx
popd is to remove the variable (reverse manner)
edited Sep 10 '11 at 20:46 answered Sep 10 '11 at 20:41 ajreal
37.3k960103
This is what I use, but I would recommend
cd -
if the person only wants to jump back and forth between to directories. gpojd Sep 10 '11 at 23:12
bookmarks.sh provides a bookmark management system for the Bash version 4.0+. It can also use a Midnight Commander hotlist.
answered Sep 11 '11 at 8:28 fgm 9,15422330
Thanks for sharing your solution, and I'd like to share mine as well, which I find more useful than anything else I've came across before. The engine is a great, universal tool: command-line fuzzy finder by Junegunn.
It primarily allows you to fuzzy-find files in a number of ways, but it also allows to feed arbitrary text data to it and filter this data. So, the shortcuts idea is simple: all we need is to maintain a file with paths (which are shortcuts), and fuzzy-filter this file. Here's how it looks: we type
cdg
command (from "cd global", if you like), get a list of our bookmarks, pick the needed one in just a few keystrokes, and press Enter. Working directory is changed to the picked item:It is extremely fast and convenient: usually I just type 3-4 letters of the needed item, and all others are already filtered out. Additionally, of course we can move through list with arrow keys or with vim-like keybindings
Ctrl+j
/Ctrl+k
.Article with details: Fuzzy shortcuts for your shell.
It is possible to use it for GUI applications as well (via xterm): I use that for my GUI file manager Double Commander. I have plans to write an article about this use case, too.
answered Jun 16 '15 at 10:22 Dmitry Frank
4,14453267
Inspired by the question and answers here, I added the lines below to my ~/.bashrc
file.With this you have a
favdir
command (function) to manage your favorites and a autocompletion function to select an item from these favorites.# --------- # Favorites # --------- __favdirs_storage=~/.favdirs __favdirs=( "$HOME" ) containsElement () { local e for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done return 1 } function favdirs() { local cur local IFS local GLOBIGNORE case $1 in list) echo "favorite folders ..." printf -- ' - %s\n' "${__favdirs[@]}" ;; load) if [[ ! -e $__favdirs_storage ]] ; then favdirs save fi # mapfile requires bash 4 / my OS-X bash vers. is 3.2.53 (from 2007 !!?!). # mapfile -t __favdirs < $__favdirs_storage IFS=$'\r\n' GLOBIGNORE='*' __favdirs=($(< $__favdirs_storage)) ;; save) printf -- '%s\n' "${__favdirs[@]}" > $__favdirs_storage ;; add) cur=${2-$(pwd)} favdirs load if containsElement "$cur" "${__favdirs[@]}" ; then echo "'$cur' allready exists in favorites" else __favdirs+=( "$cur" ) favdirs save echo "'$cur' added to favorites" fi ;; del) cur=${2-$(pwd)} favdirs load local i=0 for fav in ${__favdirs[@]}; do if [ "$fav" = "$cur" ]; then echo "delete '$cur' from favorites" unset __favdirs[$i] favdirs save break fi let i++ done ;; *) echo "Manage favorite folders." echo "" echo "usage: favdirs [ list | load | save | add | del ]" echo "" echo " list : list favorite folders" echo " load : load favorite folders from $__favdirs_storage" echo " save : save favorite directories to $__favdirs_storage" echo " add : add directory to favorites [default pwd $(pwd)]." echo " del : delete directory from favorites [default pwd $(pwd)]." esac } && favdirs load function __favdirs_compl_command() { COMPREPLY=( $( compgen -W "list load save add del" -- ${COMP_WORDS[COMP_CWORD]})) } && complete -o default -F __favdirs_compl_command favdirs function __favdirs_compl() { local IFS=$'\n' COMPREPLY=( $( compgen -W "${__favdirs[*]}" -- ${COMP_WORDS[COMP_CWORD]})) } alias _cd='cd' complete -F __favdirs_compl _cd
Within the last two lines, an alias to change the current directory (with autocompletion) is created. With this alias (
_cd
) you are able to change to one of your favorite directories. May you wan't to change this alias to something which fits your needs.With the function
favdirs
you can manage your favorites (see usage).$ favdirs Manage favorite folders. usage: favdirs [ list | load | save | add | del ] list : list favorite folders load : load favorite folders from ~/.favdirs save : save favorite directories to ~/.favdirs add : add directory to favorites [default pwd /tmp ]. del : delete directory from favorites [default pwd /tmp ].
Yes there is DirB: Directory Bookmarks for Bash well explained in this Linux Journal article An example from the article:
% cd ~/Desktop % s d # save(bookmark) ~/Desktop as d % cd /tmp # go somewhere % pwd /tmp % g d # go to the desktop % pwd /home/Desktop
@getmizanur I used your cdb script. I enhanced it slightly by adding bookmarks tab completion. Here's my version of your cdb script. _cdb() { local _script_commands=$(ls -1 ~/.cd_bookmarks/) local cur=${COMP_WORDS[COMP_CWORD]} COMPREPLY=( $(compgen -W "${_script_commands}" -- $cur) ) } complete -F _cdb cdb function cdb() { local USAGE="Usage: cdb [-h|-c|-d|-g|-l|-s] [bookmark]\n \t[-h or no args] - prints usage help\n \t[-c bookmark] - create bookmark\n \t[-d bookmark] - delete bookmark\n \t[-g bookmark] - goto bookmark\n \t[-l] - list bookmarks\n \t[-s bookmark] - show bookmark location\n \t[bookmark] - same as [-g bookmark]\n Press tab for bookmark completion.\n" if [ ! -e ~/.cd_bookmarks ] ; then mkdir ~/.cd_bookmarks fi case $1 in # create bookmark -c) shift if [ ! -f ~/.cd_bookmarks/$1 ] ; then echo "cd `pwd`" > ~/.cd_bookmarks/"$1" complete -F _cdb cdb else echo "Try again! Looks like there is already a bookmark '$1'" fi ;; # goto bookmark -g) shift if [ -f ~/.cd_bookmarks/$1 ] ; then source ~/.cd_bookmarks/"$1" else echo "Mmm...looks like your bookmark has spontaneously combusted. What I mean to say is that your bookmark does not exist." ; fi ;; # show bookmark -s) shift if [ -f ~/.cd_bookmarks/$1 ] ; then cat ~/.cd_bookmarks/"$1" else echo "Mmm...looks like your bookmark has spontaneously combusted. What I mean to say is that your bookmark does not exist." ; fi ;; # delete bookmark -d) shift if [ -f ~/.cd_bookmarks/$1 ] ; then rm ~/.cd_bookmarks/"$1" ; else echo "Oops, forgot to specify the bookmark" ; fi ;; # list bookmarks -l) shift ls -1 ~/.cd_bookmarks/ ; ;; -h) echo -e $USAGE ; ;; # goto bookmark by default *) if [ -z "$1" ] ; then echo -e $USAGE elif [ -f ~/.cd_bookmarks/$1 ] ; then source ~/.cd_bookmarks/"$1" else echo "Mmm...looks like your bookmark has spontaneously combusted. What I mean to say is that your bookmark does not exist." ; fi ;; esac }
answered Sep 4 '15 at 16:10 Al Conrad
49654
Yes, one that I have written, that is called anc. https://github.com/tobimensch/anc
Anc stands for anchor, but anc's anchors are really just bookmarks.
It's designed for ease of use and there're multiple ways of navigating, either by giving a text pattern, using numbers, interactively, by going back, or using [TAB] completion.
I'm actively working on it and open to input on how to make it better.
Allow me to paste the examples from anc's github page here:
# make the current directory the default anchor: $ anc s # go to /etc, then /, then /usr/local and then back to the default anchor: $ cd /etc; cd ..; cd usr/local; anc # go back to /usr/local : $ anc b # add another anchor: $ anc a $HOME/test # view the list of anchors (the default one has the asterisk): $ anc l (0) /path/to/first/anchor * (1) /home/usr/test # jump to the anchor we just added: # by using its anchor number $ anc 1 # or by jumping to the last anchor in the list $ anc -1 # add multiple anchors: $ anc a $HOME/projects/first $HOME/projects/second $HOME/documents/first # use text matching to jump to $HOME/projects/first $ anc pro fir # use text matching to jump to $HOME/documents/first $ anc doc fir # add anchor and jump to it using an absolute path $ anc /etc # is the same as $ anc a /etc; anc -1 # add anchor and jump to it using a relative path $ anc ./X11 #note that "./" is required for relative paths # is the same as $ anc a X11; anc -1 # using wildcards you can add many anchors at once $ anc a $HOME/projects/* # use shell completion to see a list of matching anchors # and select the one you want to jump to directly $ anc pro[TAB]
Apparix allows fast command-line file system navigation by bookmarking directories and jumping to a bookmark directly. The apparix command for jumping to a bookmark is called to. By default to can use both bookmarks and regular directory names and path names as targets. It is possible to jump to subdirectories of a bookmark in a single to invocation. All three modes, bookmarks, regular directories, and subdirectories of bookmarks, allow tab completion on the query string. Additionally, apparix supplies commands ae (apparix edit) and als (apparix ls) that can be used to invoke distant edit or listing commands on files and subdirectories in bookmarked locations. Finally, the portal command can be used to add all subdirectories of a given directory as locations bookmarked by their relative name. Examples:
to mclChange directory to the location bookmarked by mcl, say /nfs/cvs/mic/mcl/.
to mcl docChange directory to a subdirectory of that, /nfs/cvs/mic/mcl/doc.
to mcl doc/testChange directory to a further subdirectory, /nfs/cvs/mic/mcl/doc/test.
to mcl <TAB> to mcl d<TAB> to mcl doc/te<TAB>The first will generate directory completions for /nfs/cvs/mic/mcl/, the second for /nfs/cvs/mic/mcl/d, the third for /nfs/cvs/mic/mcl/doc/te.
als mcl als mcl docList the contents of /nfs/cvs/mic/mcl, /nfs/cvs/mic/mcl/doc, respectively. Tab completion acts as for to.
ae mcl TODOEdit /nfs/cvs/mic/mcl/TODO. Tab completion generates all files in the target directory matching the query pattern.
ae mcl doc/TODOEdit /nfs/cvs/mic/mcl/doc/TODO.
todo mcl todo mcl doc clog mclEdit /nfs/cvs/mic/mcl/TODO, /nfs/cvs/mic/mcl/TODO, /nfs/cvs/mic/mcl/ChangeLog, respectively. It depends on the user appreciation and needs whether such custom edit commands are useful or not.
The portal command is described in the apparix manual page.
News 2 15 Jul 09The als function (distant listing with apparix) was updated. You can now use shell expansion characters in the string optionally specified after the bookmark:
(/homes/svd) als a 'src/*.c' /homes/svd/apparix/apparix/src/apparix.cIt is necessary to quote patterns containing shell wildcards in order to prevent the current shell from trying to expand them. Find the als function here, and note that its definition is quite simple. It is easy to further customize apparix by deriving or creating your own variants of als-type bash functions.
Get apparix 3 Get the most out of apparix Bookmark projects, use subdirectory specification as in to proj data.
For subdirectory specification use tab completion.
Use now to bookmark sudden hotspots of activity and unexpected projects. Keep all now bookmarks, they mark the occasions which put you off track and will help you find those off-track locations later.
to foo .. and to foo ../bar work and change to the parent directory and sibling directory respectively.
Use todo proj to edit the TODO file for the project bookmarked proj.
Use clog proj to edit the ChangeLog file for the project bookmarked proj.
Apparix shell functionsApparix can be invoked with the option --shell-examples to get basic functions for bookmarking and jumping. However, I've added a few other functions that people may find useful, and changes to these functions occur more often than changes to apparix itself. The extended set of bash functions is available here. It is recommended to name this file for example .bash_apparix in your $HOME directory and to put the line source $HOME/.bash_apparix in your $HOME/.bashrc file.
The functionality for CSH-like shells is much more limited in comparison, mainly because of its deficiencies as a scripting language, or perhaps because of my lack of ability. It is available here.
I've had requests for ZSH apparix support. If someone writes it, please let me know. The same applies to any shell, of course.
Apparix was inspired by cdargs. The HISTORY section in the manual has a few more remarks on that. The CDargs homepage lists two more cd-related applications. These are
wcd wherever CD. This utility will scan any filesystem you throw at it. It is then possible to change/search directory by pattern and do a hundred things more. It was pointed out to me that on some Unix/Linux flavours locate does to a very large extent the same thing as wcd does - in creating a database describing file systems. Combine the locate resources with standard UNIX utilities such as grep in a small script such as goto, throw in CDargs or apparix, and your setup is small, adaptible, powerful, and uses existing resources. Still, I've tried wcd and it delivers what it promises.
kcd k CD. Seems similar to CDargs. I've not been able to track the meaning of k. Possibly it is just the first initial of the author, Kriang Lerdsuwanakij. Hopefully it is not in the long and lamentable tradition of KDE kapplikations with klunky knames.
See also Sitaram Chamarty's bash goto functions.
Miscellaneous cd -takes you to the previous directory. The apparix equivalent is to - and does the same.
cd `pwd`erases any symlink side-effects that your path may suffer from. Well, that's what I thought. I've now found a a more correct statement is pwd may erase symlink side-effects that your path suffers from.
Pattern-based cd with gotoSitaram Chamarty wrote a bash goto function that leverages the locate database or a user-created dump of file system locations. This is very useful for a) browsing and searching (new) file systems b) visiting locations in a hugely branched file hierarchy or when you want to range over many destinations (so that the bookmark approach is not a good fit) c) on systems where you somehow have such a minimal presence that you do not want to bother installing whatever file system navigation tools you normally use.
It is possible to ask for locations by directory name pattern and file name pattern, and it is possible to restrict matches to a specified directory that will act as root for the query.
goto can be thought of as a very convenient chimera of find and cd. It is complementary to bookmarking in that the latter provides unambiguous and instantaneous change of directory to what is presumably an oft-visited hotspot, where the mark is independent of its associated destination. goto can take you anywhere but may require zooming in by means of a selection menu, depending on the distinctiveness of the query string. The latter is used to match destinations directly.
Go to Sitaram's goto page.
WCD is a directory changer for DOS and Unix. Another NCD (Norton Change Directory) clone. This program jumps to a (sub)directory anywhere in the directory-tree. The directory to jump to can be given by... only the first characters or an expression with wildcards
Does anybody else remember NCD.exe? This is a way old school command-line utility written in the mid-eighties. It built a databaose of the directories on your hard drive, then when you typed ncd <foo> it would try to get a partial match against the database. Where there were multiple matches, a little ANSI graphics box popped up and allowed you to use the cursor to select the right folder. Once the folder is selected, your working directory is changed. Very simple and to the point.I dont know why I got to thinking about it. I used to collect utilities like this back in the DOS days but as I got into Windows that became less and less important. But now Im always in a powershell console and I find myself missing this sort of tool. I found a very informative (if confused and rambling) webpage on the topic which brought back some old memories. Theres a bunch of clones of NCD, I found one called WCD released as recently as 2006 which is available for several different shells.
Seems this sort of thing would be well within the realm of a PowerShell utility. A bit beyond my own skills perhaps, or at least my interest in learning how to write at the moment. But maybe someone else will be inspired.
Comments
bitbyte 2008-03-13 09:00:37WCD in PowerShell: if youre wiling to use the -j option, you can use the following wcd.ps1 script:wcdwin32 $args -GN -j | %{$_ -replace ,} | sl
This week's "Cool Tool" is CDargs, a browser and bookmark utility for all of you Unix command-line commandos. CDargs is an extension to the cd, or "change directory" command, that lets you quickly navigate to the farthest corners of your filesystem. As the author says, CDargs is for "... when even the almighty and wonderful tab-completion is too much typing." (And CDargs also supports tab-completion.)To get started, first reference the path to examples/cdargs-bash.sh in your ~/.bashrc:
source /usr/share/doc/cdargs/examples/cdargs-bash.shThen, open the CDargs browser:
$ cdargs [. ] /home/carla 0 [1writin-g] /home/carla/1writing 1 [Desktop ] /home/carla/Desktop 2 [Mail ] /home/carla/Mail 3 [Maildir ] /home/carla/Maildir 4 [archive ] /home/carla/archive 5 [bin ] /home/carla/bin ...Navigate with the arrow keys, and hit return to select. Toggle using the tab key to switch between Browse and List modes. List mode contains your own custom bookmarks, which you create in a plain text file, or by using CDarg's built-in commands.
CDargs also works with the tcsh shell. It is released under the GPL, so anyone who wishes to adapt it for other shells can go for it. Read all about it at the CDargs home page.
The code is really bad, I know that. It was written during that phase when you start learning C++ after coding in C for quite a while... This is just another reason for never touching it again (unless, of course, I receive fixes for bugs not detected yet.)I'd like to include some ZSH-code for completion into the distribution but I don't use ZSH and thus I won't write it.
Current Version: 1.35
CDargs heavily enhances the navigation of the common unix file-system inside the shell. It plugs into the shell built-in cd-command (via a shell function or an alias) and thus adds bookmarks and a browser to it. It enables you to move to a very distant place in the file-system with just a few keystrokes. This is the kind of thing that power shell users invent when even the almighty and wonderful TAB-completion is too much typing. (Just as a side-note: there exists TAB-completion for cdargs ;-)
This little piece of software was inspired by an article Michael Schilli wrote for the German iX-Magazine]. There he showed a script which let you choose from a list of alternatives were to cd to, e.g. in your xterm. In the forum connected to this article some others enhanced this script.
When I wanted to change it even more and put some more features in it I discovered that it was not under the GPL so I decided to do a complete rewrite of the whole thing. Since I wanted to make sure that I shared no code with the original artwork I chose to use C/C++ together with the ncurses library. This program is the result of those efforts.
Actually
- Claus Brunzema
- Dan Allen
were heavily involved in this project. Please read the THANKS file in the distribution for a full list of contributors. It's amazing that such a small program can have so many people helping it.
Closebracket lets you define multiple shell actions in a single command to speed up the typing of the most repetitive shell commands. It includes ']' and '][' commands, which are located near the "Enter" key and are easy to type quickly. They invoke primary and secondary actions respectively.
cdll Bash scripts A replacement for cd. Keeps unlimited history, setup special directories for quick access cdll allows easy moving about between directories. When changing to a new directory the current one is automatically put onto a stack. By default 50 entries are kept but this is configurable. Special directories can be kept for easy access - by default up to 10 but this is configurable. The most recent stack entries and the special entries can be easily viewed.
The directory stack and special entries can be saved to, and loaded from, a file. This allows them to be set up on login, saved before logging out or changed when moving project to project.
In addition, cdll provides a flexible command prompt facility that allows, for example, a directory name in colour that is truncated from the left if it gets too long.
Do you realize how many times you type cd per day? Do you realize how many times you retype the same directory names again and again? Ever since I migrated from 4DOS/NT shell on Windows to using Bash on Unix platforms, I've missed its cd history access. In 4DOS/NT the history of the visited directories can be navigated by Ctrl+PgUp/Dn. Every time you go to a new directory by cd, its name automatically goes on top of an easily accessible history list.
In Bash, cd - switches between the last two directories. This is a function in the right direction but many times I wanted to go to the directory before the last, I dreamed of something like cd -2.
A little scripting creates some sanity in the directory navigation of Bash.
Installing the CD history function
To install the modified CD function, copy acd_func.sh to any directory in your $PATH, or even your home directory. At the end of your .bashrc add source acd_func.sh. Restart your bash session and then type cd --.
lotzmana@safe$ cd -- 0 ~Type cd -- to verify if the installation works. Above you may see the result 0 ~. This shows that you have one directory in your history.
lotzmana@safe$ cd work lotzmana@safe$ cd scripts lotzmana@safe$ pwd /home/petarma/work/scripts lotzmana@safe$ cd -- 0 ~/work/scripts 1 ~/work 2 ~ lotzmana@safe$ cd -2 lotzmana@safe$ pwd /home/petarmaThe cd command works as usual. The new feature is the history of the last 10 directories and the cd command expanded to display and access it. cd -- (or simply pressing ctrl+w) shows the history. In front of every directory name you see a number. cd -num with the number you want jumps to the corresponding directory from the history.
How CD with history works
lotzmana@safe$ nl -w2 -s' ' acd_func.sh 1 # do ". acd_func.sh" 2 # acd_func 1.0.5, 10-nov-2004 3 # petar marinov, http:/geocities.com/h2428, this is public domain 4 cd_func () 5 { 6 local x2 the_new_dir adir index 7 local -i cnt 8 if [[ $1 == "--" ]]; then 9 dirs -v 10 return 0 11 fi 12 the_new_dir=$1 13 [[ -z $1 ]] && the_new_dir=$HOME 14 if [[ ${the_new_dir:0:1} == '-' ]]; then 15 # 16 # Extract dir N from dirs 17 index=${the_new_dir:1} 18 [[ -z $index ]] && index=1 19 adir=$(dirs +$index) 20 [[ -z $adir ]] && return 1 21 the_new_dir=$adir 22 fi 23 # 24 # '~' has to be substituted by ${HOME} 25 [[ ${the_new_dir:0:1} == '~' ]] && the_new_dir="${HOME}${the_new_dir:1}" 26 # 27 # Now change to the new dir and add to the top of the stack 28 pushd "${the_new_dir}" > /dev/null 29 [[ $? -ne 0 ]] && return 1 30 the_new_dir=$(pwd) 31 # 32 # Trim down everything beyond 11th entry 33 popd -n +11 2>/dev/null 1>/dev/null 34 # 35 # Remove any other occurence of this dir, skipping the top of the stack 36 for ((cnt=1; cnt <= 10; cnt++)); do 37 x2=$(dirs +${cnt} 2>/dev/null) 38 [[ $? -ne 0 ]] && return 0 39 [[ ${x2:0:1} == '~' ]] && x2="${HOME}${x2:1}" 40 if [[ "${x2}" == "${the_new_dir}" ]]; then 41 popd -n +$cnt 2>/dev/null 1>/dev/null 42 cnt=cnt-1 43 fi 44 done 45 return 0 46 } 47 alias cd=cd_func 48 if [[ $BASH_VERSION > "2.05a" ]]; then 49 # ctrl+w shows the menu 50 bind -x "\"\C-w\":cd_func -- ;" 51 fi4-7: cd_func() is a function, variables are declared local and are automatically deleted at the end of the function
8-11: if the function is called with a parameter "--" then it dumps the current content of the directory history. It is stored in the same place pushd/popd keep names -- the directory stack. Storage is the same, access is different.
12-13: Argument $1 is transferred into $the_new_dir for some post-processing. Immediately after that, if there are no parameters we assume that user asked for his home directory.
14-22: If parameter begins with '-' then the user is attempting to access one of the names in the history list. $index gets the number of the directory, then we extract the corresponding name into $adir. For example, dirs +3 dumps directory #3 from the stack.
At this point in $the_new_dir we have either a name specified explicitly as a parameter or a name obtained from the history of previously visited directories.
23-25: If a directory name begins with '~' then this character has to be replaced by the actual home directory name.
26-30: pushd does the actual 'cd'. It also puts the name on top of the directory stack. stdout is redirected to /dev/null in order to completely imitate how 'cd' works. Notice that any output to stderr, for example a message telling that the directory specified by the user doesn't exist will show up, which is again similar to what 'cd' does. The function aborts if pushd fails. We also need the new directory name for further analysis and $the_new_dir carries it down the function.
31-33: Keeping track of more than 10 directories is unproductive. Since we have just pushed one on top of the stack, we trim off any that fall below 11 names deep.
34-44: We loop through all the names in the directory stack. Any name that matches the new current directory is eliminated. Again, we have to translate any name from the list which begins with '~' to its format of fully expanded home directory.
47: We assign cd to be cd_func().
48-51: If the bash version allows for macros to be assigned we make ctrl+w summon the history of visited directories.
This script defines a function. It must be sourced and not executed, so that cd_func() is parsed and stored in the current environment. Try env and you must see it after all environment variables.
Documentation page of the script
Visit the acd_func.sh man page.
For comments on this article please visit or join zepp mailing list.
The text of this page is public domain.
Since I moved to Win XP my old and trusted companion for easily jumping between different spots in the directory tree, NCD (Norton Change Directory) has ceased to work.
NCD worked by building a database and by using NCD to make and remove directories, the database could be kept in sync, well almost anyway.
If the directory you wanted to go to had a unique name all you had to type was NCD dir_name but if it was a common name like test you might have had to recall the commandline one or more times to get to the destination.
Another approach would be to note that if you consider part of or the whole branch, from root to the destination, the situation will be less ambigous or even unique Using that idea I came up with this simple solution which IMHO works quite well. The user interface may be rendered idiosyncratic by some, but I welcome you to suggest improvements. The documentation is nothing fancy just a few examples included in the code. The program is tested under Win XP, but I think it could work on other OS's with some minor tweaks. PS. As directory delimiter "\", "/" or even "," can be used. The comma is due to laziness, because on the Swedish keyboard one has to use Shift or Alt Gr key to get slashes!!
So instead of typing
cd "C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\Machin eKeys"
at the DOS prompt, typing the more dense command of
a ,d,a,a,m,c,r,m
will suffice. Or even horrors a ,d,,,,,r,m ;-), but that one is tougher on the filesystem.@perl -Swx %0 %* @c:\a_cd.bat @goto :eof #!perl # # Utility for quickly changing directory # Named to "a.bat" in homage to Pr1mOS's change working directory comm +and *a* (attach) ;-] # # Syntax: # a ,wi,ja,pa ===> cd \Windows\java\Packages # a ...\me ===> cd \Windows\Media # a ===> cd \Windows\Media\Microsoft Office 2000 *OR* a se +lection of subdirectories # a / ===> cd \ # a mys,d,* # [a] /mysql/data/mysql/ # [b] /mysql/data/tast/ # [c] /mysql/data/test/ # [d] /mysql/Docs/Flags/ # select: # # if ambigous the correct target is selected with alpha keys /a .. zz/ # # Versions: # 0.2 2003-02-22 Cleanup # 0.1 2003-01-31 First working # 0.0 2003-01-15 Start of Coding # use strict; use warnings; use Cwd; my $DEBUG = 0; my $DELIM = qr{,|\\|\/}; ## Either "," or "/" or \" my @to = @ARGV ? split(/$DELIM/, $ARGV[0] ) : (); my @cwd = split(/$DELIM/, cwd); shift @cwd; # Remove disk unless ( @ARGV ) { push @to, @cwd, '*'; } elsif ( $ARGV[0] =~ /^$DELIM/ and not @to ){ } elsif ( $to[0] eq '' ) { shift @to; } else { unshift @to, @cwd; } ## Lazy-dots foreach my $part (0 .. $#to) { if ( $to[$part] =~ /\.(\.+)/ ) { $to[$part] = join('/', ('..') x length($1)); } } @to = split(/\//, join('/', @to)); ## Rel2Abs my @fixed; for (@to) { if ($_ eq '..') { pop @fixed if @fixed; } elsif($_ eq '.') { ## Skip } else { push @fixed, $_ } } my @choices = expand('/', @fixed); my %hash; my $enum = 'a'; my $choice = ''; if (1 == @choices) { # Autoselect if only one item to choose $hash{a} = $choices[0]; $choice = $enum; } elsif(1 < @choices) { foreach my $c (@choices) { ($hash{$enum} = $c) ; print '[', $enum++, "] $c\n"; } print "select: "; $choice = <STDIN>; chomp $choice; } # Create a batch file to change the directory in the shell. open (CD, '>', 'C:/A_CD.BAT') or die "Failed to create CD bat file $!\ +n"; if ( defined $hash{$choice} ) { $hash{$choice} =~ s/\//\\/g; # Make windows happy print CD "\@CD \"$hash{$choice}\"\n"; } else { print CD "\@echo No match\n"; } close CD; sub expand { my ($bough, @twigs) = @_; return $bough unless @twigs; ## Looked it up in the thesaurus ;-] opendir(my $dh, $bough) || die "Can not check $bough for twigs due + to $!\n"; my $regexp = shift @twigs; $regexp =~ s/\*/.*/; my @found; foreach my $f ( grep { $_ =~ /^$regexp/i and $_ !~ /^\./} readdir +($dh) ) { push @found, expand("$bough$f/", @twigs) if (-d "$bough$f"); } closedir($dh) || die "Bad close for $bough $!\n"; return @found; } __END__
My good old Norton Change Directory (©1988 ) choked on a disc having 15 000 directories, the weakling. Then I had to do what I do every time I want something to be done well : I rewrote it myself.
No size limit, unlike ACD (boo !). I imitated the behavior of Norton CD, in particular, if you type several times "NCD TMP", NCD will trot you through all TMP directories on the hard disk in turn. You do not remain stuck on the first one.
Also, the disk is rescanned automatically if NCD is launched from a directory created since last scanning or from its parent. And of course, I added my fabulous fuzzy search as usual, quite convenient for the mistypings which are thus "forgiven" (Norton CD only goes to the directory having the longest common beginning).
On the other hand it is not optimized (for the moment) : a large file, NCD.NCD, is placed in the root of each hard disk. It will shrink in later versions.
Soon also, indexing of CD-ROMs.
Click here Size : 50 kB.
Directory Maven 95 is an automated change directory program. Like the DOS version, you can quickly change to any directory on any drive from the MS-DOS command line or view the directory trees of all your drives. However, Directory Maven 95 is a 32-bit console application that supports long filenames and up to 10,000 directories per drive. This program is freeware: Try it!
Coig Change Directory (CCD) is a freeware DOS enhanced directory changer. It allows you to change to any directory in your drives quickly, and without typing long CD commands from the command line.
CCD can be used with arguments from the command line or by using its user-friendly graphical interface, where you can navigate through the directory tree with the cursor keys.
Fergal's ncd Script February 2003 #!/usr/bin/ksh # # Fergal Goggin 11-April-2000, SSL # ncd : a change directory script for UNIX. works like norton change # directory on a PC. It can take regular expressions on the # command line. Remove $HOME/.ncd if you want to change the # database. Use env var BASEDIR to specify the top level directory # in the tree (defaults to the root dir, /) # # usage: [BASEDIR=XXX] ncd - to create, remove $HOME/.ncd first # ncd- to search # BOLD_TYPE="" NORMAL_TYPE="" INVERSE_TYPE="" if [ $TERM = "xterm" ] then BOLD_TYPE="[1m" NORMAL_TYPE="[0m" INVERSE_TYPE="[7m" fi NCDDATABASE=$HOME/.ncd.`uname -n` NCDTMPFILE=/tmp/$$.ncd if [ "$BASEDIR" = "" ] then BASEDIR=/ fi if [ ! -f $NCDDATABASE ] then echo "re-creating database from $BASEDIR" find $BASEDIR -type d 2> /dev/null | gzip > $NCDDATABASE elif [ $# -lt 1 ] then echo "ncd, change directory for UNIX, fgoggin 2000" echo "usage: [BASEDIR=XXX] ncd " else zgrep $1 $NCDDATABASE > $NCDTMPFILE trap 'rm -f $NCDTMPFILE' 2 noLines=0 # wc -l seems to stick a tab in front of it output # so it is just as easy to use grep -c noLines=`grep -c ^ $NCDTMPFILE` if [ $noLines -eq 0 ] then echo "No match" elif [ $noLines -eq 1 ] then # exact match cd `cat $NCDTMPFILE` else # list all directories found and let the user pick one directorySelected="" PS3="${INVERSE_TYPE}Pick one from the above list${NORMAL_TYPE} > " select directorySelected in `cat $NCDTMPFILE` do if [ "$directorySelected" = "" ] then # when the user wants to break out of the # display loop without changing directory. case "$REPLY" in "q"|"Q"|"quit"|"Quit"|"QUIT"|"E"|"e"|"X"|"x"|"exit"|"Exit"|"EXIT") break esac echo "${BOLD_TYPE}not valid${NORMAL_TYPE}" # force list to be re-displayed REPLY="" else cd $directorySelected # break out of select loop break fi done fi fi rm -f $NCDTMPFILE BASEDIR=""
NCD.EXE 5,592 bytes
KeN's Change Directory. If you like jumping to different directories quickly, you should try my version of the program, based on one of my favorite Norton Utilities. My NCD program is extremely small and fast. One cool feature is that it stores the entire directory tree (skips hidden directories) in the "NCD.EXE" program file itself. This keeps your HD from getting cluttered and makes the program load even faster. DOS16
Changing Directories with ncd
This month, Fergal Goggin submits Korn/Bash script ncd, a Unix version of the Norton change directory utility. Instead of typing in long directory paths, using regular expressions, ncd greps a file for matches. If ncd finds more than one match, the user is prompted to choose the required directory.
After Fergal describes ncd, I contrast the ncd solution with Fred Brunet's article, fcd: a Smart Change Directory (Sys Admin, November 1994), and I include my testing results.
[Nov 26, 2004] kcd Home Page
KCD is the most interesting Linux implementation of NCD functionality with some novel ideas. Actively supported. Highly recommended.
kcd is a directory change utility under Linux or any other Unix clones. It helps you navigate the directory tree. You can supply the desired directory name in the command line and let kcd find it for you or let kcd show the entire directory tree and use arrow keys to go to the destination directory.
Here is a list some features available in kcd:
- Fast directory rescanning. All directory timestamp is saved so that certain directories do not need rescanning if they are not changed.
When you supply directory in command line and kcd find too many matches. kcd shows all of them and let you select using cursor keys. You can tell kcd to skip some directory. You can also chose whether you want the whole directory tree, inside your home directory, etc. They can be set in kcd configuration file. Supports bash, ash, pdksh, zsh and tcsh. Multiple configuration profiles. Priority directory matching via bookmark. Fuzzy directory searching (Contributed by Robert Sandilands). Supports UTF-8 Unicode encoding with combining characters. Supports localization. Default, vi, and emacs key binding modes. Partial directory tree display. Display directory tree without saved data. kcd is available as stable version and development version. You can distinguish development version from stable version by looking at its version number. Beginning from version 5.0.0, any version x.y.z where y is even is a stable version. Those where y is odd is a development version. Features currently present in the development version will eventually appear in the future stable version 8.0.0.
kcd is distributed in source form under General Public License (GPL).
The program and this web page is maintained by Kriang Lerdsuwanakij
Recommended Links
Google matched content
Softpanorama Recommended
public-ftp-pub-linux-utils-shell
- gd-1.2.2.tar.gz (LSM entry) 1998-07-05 change to directories w/ just the last dir name (6079 bytes) ;
- locatedir by Alexander Kourakos (BASH, tcsh, or csh; find & sort commands.)
- ncd-0.9.8.lsm
- kcd-6.11.0.lsm
- qprompt-2.3.lsm -- utility to process raw keyboard keystrokes
- rcd.readme fancy Change Directory program (122880 bytes)
- xd change's directories based on incomplete specs.
Norton Change Directory (NCD) clones
- Fergal Goggin submits Korn/Bash script ncd, a Unix version of the Norton change directory utility. Instead of typing in long directory paths, using regular expressions, ncd greps a file for matches. If ncd finds more than one match, the user is prompted to choose the required directory.
- Fred Brunet's fcd script (fcd: A Smart Change Directory) shares the same goal as Fergal's ncd build a database of full path directories, search the database, and allow the user to choose the correct directory.
DirB, Directory Bookmarks for Bash Linux Journal
GitHub - b4b4r07-favdir Save favorite directory on bash and zsh
bashnavigation.sourceforge.net
Etc
Society
Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers : Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism : The Iron Law of Oligarchy : Libertarian Philosophy
Quotes
War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda : SE quotes : Language Design and Programming Quotes : Random IT-related quotes : Somerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose Bierce : Bernard Shaw : Mark Twain Quotes
Bulletin:
Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 : Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law
History:
Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds : Larry Wall : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOS : Programming Languages History : PL/1 : Simula 67 : C : History of GCC development : Scripting Languages : Perl history : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history
Classic books:
The Peter Principle : Parkinson Law : 1984 : The Mythical Man-Month : How to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Haters Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite
Most popular humor pages:
Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor
The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D
Copyright © 1996-2021 by Softpanorama Society. www.softpanorama.org was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.
FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.
This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...
You can use PayPal to to buy a cup of coffee for authors of this site Disclaimer:
The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the Softpanorama society. We do not warrant the correctness of the information provided or its fitness for any purpose. The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.
Last modified: February, 21, 2017
From the man bash page:
With this set, if I give the following bash command:export d="/Users/chap/Desktop"
I can then simply type
cd d
to change to my Desktop directory.