Wade Wade - 1 year ago 70
Linux Question

Change cd default directory (bash)

I'm looking for a way to change the default directory of cd, and I'm wondering if this is possible. I tried adding

alias "cd=cd ~/Documents/Github" 

to .bashrc, but this obviously doesn't work because it breaks the cd command so that you cannot use cd for anything but going to that directory. Is there some export that I could put in .bashrc to do this? I do not want to change my home directory, just the default directory cd goes to. I ask because I regularly use cd to change to my default directory that I am programming in and would like to not have to type
cd ~/workspace
and then
cd workspace
every time I want to change to the directory

Answer Source

Here's a simpler alternative using an alias:

alias cd='HOME=~/Documents/Github cd'
  • While this redefines $HOME, it does so ONLY for the cd command, so should be safe(*).
  • This also obviates the need for any custom parameter pre-parsing.

If you place this in ~/.bashrc, you should get the desired behavior.

Note that, by default, this alias will NOT be in effect in scripts (non-interactive shells), as alias expansion is by default disabled there (use shopt -s expand_aliases to explicitly enable).

(*) @chepner points out one restriction: with the alias in place you won't be able to do HOME=/somewhere/else cd, i.e., you won't be able to redefine (override) $HOME again, ad-hoc. As he further states, though, it's hard to imagine why anyone would want to do that.