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
or cd
and then cd workspace
every time I want to change to the directory ~/workspace
.
Here's a simpler alternative using an alias:
alias cd='HOME=~/Documents/Github cd'
$HOME
, it does so ONLY for the cd
command, so should be safe(*).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.
You can shadow the builtin cd
command with a shell function. Add the following to your .bashrc
file.
cd () {
if [ $# = 0 ]; then
builtin cd ~/Documents/Github
else
builtin cd "$@"
fi
}
This isn't perfect, as it assumes you will never call the function as
* cd -L
* cd -P
* cd -LP
* etc
(that is, using one or more of the supported options without an explicit directory.)
UPDATE
This might be a little more comprehensive, but I haven't tested it.
cd () {
local -a args
while getopts LP opt "$@"; do
case $opt in
-*) args+=( "$opt" ) ;;
esac
done
shift $((OPTIND-1))
# Assume at most one directory argument, since
# that is all cd uses
args+=( "${1:-~/Documents/Github}" )
builtin cd "${args[@]}"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With