Softpanorama

May the source be with you, but remember the KISS principle ;-)
Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and  bastardization of classic Unix

CDPATH

News Advanced Unix filesystem navigation Recommended Links ln Command completion  History Substitution pushd/popd/dirs
Norton Change Directory
(NCD) clones
OFM Dotfiles Unix shells history Unix Shell Tips and Tricks Humor Etc

The shell variable CDPATH is a useful but extremely underutilized and often misunderstood feature of ksh and bash.

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

This variable is similar to PATH and provides is a list of paths that the "cd" command will search for whatever subdirectory you provide as its argument. For example, if you can have:

export CDPATH=".:~:~public_html"

you can "cd" to any of the subdirectories in the /var or /etc by typing cd [subdirectory] without typing the entire path - regardless of your current directory. Among the most natural candidates for the includtion into  $CDPATH are:

So the initial CDPATH might look like :

	export CDPATH='/etc/:/var/:./:~/:../:../../:~/fav/'

What happens if we have a local directory with the same name as one of the others defined in $CDPATH? What I have found that in ksh and bash:

  1. If you put a trailing slash "/" on each path in $CDPATH, you'll "cd" to the local directory.
  2. If you don't put a trailing slash on each pathname, you'll "cd" to the first pathname in the $CDPATH list that contains a matching subdirectory.  In this case you need to cd to local directory using cd ./name. Or you  can use directory completion for any local directory which actually is not a bad idea...

that means that it's a very good idea to use those trailing slashes if you want to change to local subdirectories.

It's a very good idea to use those trailing slashes if you want to change to local subdirectories.

Also note that CDPATH concept works for partial pathnames too. If you have a /usr/local/lib/X11 directory, cd lib/X11 is a shortcut to this location for the given example.

Dr. Nikolai Bezroukov


Top Visited
Switchboard
Latest
Past week
Past month

NEWS CONTENTS

Old News ;-)

Setting Your $CDPATH

quote from O'Reilly book Safari Books Online - 0596526784 - bash Cookbook, 1st Edition

16.5.1. Problem

You want to make it easier to switch between several directories in various locations.

16.5.2. Solution

Set your $CDPATH appropriately. Your commonly used directories will likely be unique, so for a contrived example, suppose you spend a lot of time working with init's rc directories:

	/home/jp$ cd rc3.d
	bash: cd: rc3.d: No such file or directory

	/home/jp$ export CDPATH='.:/etc'

	/home/jp$ cd rc3.d
	/etc/rc3.d

	/etc/rc3.d$ cd rc5.d
	/etc/rc5.d

	/etc/rc5.d$

	/etc/rc5.d$ cd games
	bash: cd: games: No such file or directory

	/etc/rc5.d$ export CDPATH='.:/etc:/usr'

	/etc/rc5.d$ cd games
	/usr/games

	/usr/games$

16.5.3. Discussion

According to the bash Reference, $CDPATH is "a colon-separated list of directories used as a search path for the cd built-in command." Think of it as $PATH for cd. It's a little subtle, but can be very handy.

If the argument to cd begins with a slash, $CDPATH will not be used. If $CDPATH is used, the absolute pathname to the new directory is printed to STDOUT, as in the example above.


Warning: Watch out when running bash in POSIX mode (e.g., as /bin/sh or with --posix). As the bash Reference notes:"If $CDPATH is set, the cd built-in will not implicitly append the current directory to it. This means that cd will fail if no valid directory name can be constructed from any of the entries in $CDPATH, even if a directory with the same name as the name given as an argument to cd exists in the current directory."To avoid this, explicitly include . in $CDPATH. However, if you do that, then another subtle point noted in the bash Reference comes into play:"If a nonempty directory name from $CDPATH is used, or if '-' is the first argument, and the directory change is successful, the absolute pathname of the new working directory is written to the standard output."In other words, pretty much every time you use cd it will echo the new path to STDOUT, which is not the standard behavior.

Common directories to include in $CDPATH are:

.

The current directory (see the warning above)

~/

Your home directory

..

The parent directory

../..

The grandparent directory

~/.dirlinks

A hidden directory containing nothing but symbolic links to other commonly used directories

The above suggestions result in this:

	export CDPATH='.:~/:..:../..:~/.dirlinks'

16.5.4. See Also

Saving Time When You Change Directories: cdpath

From Unix Power Tools by By Shelley Powers, Jerry Peek, Tim O'Reilly. O'Reilly, 2002

Some people make a shell alias (Section 29.2) for directories they cd to often. Other people set shell variables (Section 35.9) to hold the pathnames of directories they don't want to retype. But both of those methods make you remember directory abbreviations — and make you put new aliases or shell variables in your shell startup files (Section 3.3) each time you want to add or change one. There's another way: the C shell's cdpath shell variable and the CDPATH variable in ksh, bash, and some versions of sh. (zsh understands both cdpath and CDPATH.) I'll use the term "cdpath" to talk about all shells.

When you type the command cd foo, the shell first tries to go to the exact pathname foo. If that doesn't work, and if foo is a relative pathname, the shell tries the same command from every directory listed in the cdpath. (If you use ksh or sh, see the note at the end of this article.)

Let's say that your home directory is /home/lisa and your current directory is somewhere else. Let's also say that your cdpath has the directories /home/lisa, /home/lisa/projects, and /books/troff. If your cd foo command doesn't work in your current directory, your shell will try cd /home/lisa/foo, cd /home/lisa/projects/foo, and cd /books/troff/foo, in that order. If the shell finds one, it shows the pathname:

% cd foo
/home/lisa/foo
%

If there is more than one matching directory, the shell uses the first match; if this isn't what you wanted, you can change the order of the directories in the cdpath.

Some Bourne shells don't show the directory name. All shells print an error, though, if they can't find any foo directory.

So, set your cdpath to a list of the parent directories that contain directories you might want to cd to. Don't list the exact directories — list the parent directories (Section 1.16). This list goes in your .tcshrc, .cshrc, or .profile file. For example, lisa's .tcshrc could have:

~ Section 31.11

set cdpath=(~ ~/projects /books/troff)

A Bourne shell user would have this in his .profile file:

CDPATH=:$HOME:$HOME/projects:/books/troff
export CDPATH

A bash user might have it in her .bashrc or .bash_profile.

(If your system doesn't define $HOME, try $LOGDIR.)

Note that the Bourne shell CDPATH in the above example starts with a colon (:) — which, as in the PATH variable, is actually an empty entry (Section 35.6) that stands for "the current directory." Both the sh and ksh I tested required that. Without an empty entry, neither sh or ksh would cd into the current directory! (bash seemed to work like csh, though.) You could actually call this a feature. If there's no empty entry in CDPATH, a user has to use cd ./subdirname to go to a subdirectory of the current directory.

—JP and SJC

Bash Tips and Tricks- 'cd' with style

Another interesting trick is the $CDPATH variable. Similar in nature to the $PATH variable, it allows an argument to the 'cd' command to be considered not only in the current working directory, but in an ordered list of directories!

It is not straightforward to see the utility of this feature, but bear with me. Each user has a particular area of interest on a given Linux system. A system administrator (root) would be interested in /etc and /var/log. A home desktop user (joe) would be interested in ~/Documents. Someone at work (juser) might spend most of his or her time in a /usr/local/projects directory.

So, by placing each user's commonly visited paths in that user's $CDPATH variable, one can change to a known subdirectory without first having to navigate there! For example:

(pwd = /home/juser)

cd /usr/local/projects/abc
vs.
cd abc
(pwd = /usr/local/projects/abc)

(pwd = /usr/local/projects/abc/src/db/old/migration/)
cd ../../../..
vs.
cd abc
(pwd = /usr/local/projects/abc)

Indeed, one can find many subtle uses for this feature. A reasonable list to start with on a Red Hat Linux system, for example, might be

.:~:~/docs:/mnt:/usr/src/redhat:/usr/src/redhat/RPMS:/usr/src:/usr/lib:/usr/local

*NOTE: An empty entry ('::' or a leading or trailing ':') in $CDPATH (or in $PATH) is interpreted as the current working directory!


Something you may have seen before in other systems (the much maligned SCO OSes, for example) is this handy option:

shopt -s cdspell

"This will correct minor spelling errors in a 'cd' command, so that instances of transposed characters, missing characters and extra characters are corrected without the need for retyping."

[jason@localhost jason]$ cd Documnts
Documents
[jason@localhost Documents]$
[jason@localhost jason]$ cd documents
Documents
[jason@localhost Documents]$

Unfortunately, it's flexibility is rather limited...

[jason@localhost jason]$ cd document
bash: cd: document: No such file or directory
[jason@localhost jason]$

Recommended Links

Google matched content

Softpanorama Recommended

Please visit  Heiner Steven SHELLdorado  the best shell scripting site on the Internet

Advanced Bash-Scripting Guide

Advanced Unix filesystem navigation

bash Tips and Tricks

Pushd, popd and dirs

Bash and ksh93 Shell Prompts Customarization

Unix Shell Tips and Tricks

 



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 quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard 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 DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting 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-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Hater’s 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 05, 2017