IN-Decent

Re-decentralizing internet with free software

Use CDPATH Env Variable to Fast Switch Directories

Posted at — May 29, 2021

cd command and cd builtin provided by various shells use a special environment variable called CDPATH which takes a PATH like colon(:) separated list of directories to search for the directory given as an argument.

This CDPATH variable is only used if the directory passed as argument to cd does not precede with a ‘/’ directory separator.

CDPATH environment variable is used as shown below,

#set CDPATH with paths to search for frequently used directories
CDPATH=.:$HOME:$HOME/.conf:/opt/projectdir
export CDPATH

#below cmd will switch to bin dir in $HOME if its not in current dir instead of throwing error
cd bin

NOTE:

  • When CDPATH is set, cd will first search in the given path list before looking in current directory. So always use current directory(.) as fist path in the list to avoid surprises and look in current directory before looking elsewhere
  • Whenever cd switches path using CDPATH, it will print full path of the directory in sdtout, so this change in default behaviour might affect your scripts if not taken care.

References:

  1. man cd
  2. bash manual for cd builtin