Wednesday, February 7, 2007

Preserve directory when change drive in cygwin

In cygwin, you can use "cd c:" or "cd d:" to change to different drives. However, it always change to the root directory of the drive. In Windows command prompt you have a nice feature that the c: or d: will change to the directory that you previous stayed in that drive. For example:
C:\Program Files\Mozilla Firefox\extensions>d:
C:\Program Files\Mozilla Firefox\extensions>

However, in bash, you just can't do this

extensions>cd d:
d>cd c:

Here I add some aliases to implement this feature in bash. Add the following lines in $HOME/.bashrc:

export PWD_c=c:/
export PWD_d=d:/
export PWD_e=e:/
alias c:='export PWD_`expr substr "$PWD" 11 1`="$PWD";cd "$PWD_c"'
alias d:='export PWD_`expr substr "$PWD" 11 1`="$PWD";cd "$PWD_d"'
alias e:='export PWD_`expr substr "$PWD" 11 1`="$PWD";cd "$PWD_e"'

You may need to add more PWD_x environment variables and alias in case you have more drive. Make sure you have the quotes (") because of the spaces in long file name.