Aliases aren't meant to do this, but you can create a function called cd
that is a wrapper for the real cd
. This one works for me! Just put it into your .bash_profile
or your profile file of choice.
cd () { if [ "$1" = ",," ]; then builtin cd ..; else builtin cd "$@"; fi; }
Or, with comments and pretty formatting:
cd ()
{
if [ "$1" = ",," ]; then # if first argument is ",,"...
builtin cd .. # call the builtin cd with ".." instead...
else
builtin cd "$@" # else call builtin cd with original arguments
fi
}
EDIT
Thanks @derobert for pointing out that if then else
is better here than && ||
. Also, I just realized (*facepalm*) that this implementation will only work if any non-path arguments (i.e. -L -P
) are not the first argument. So be warned, if you have a bad habit of typing cd -L ,,
this isn't going to help you. And that is non-trivial to handle correctly, I think.
6An alias is a program to run, not an argument to the program; so
$ ,,
would complain, as such:bash: ..: Is a directory
. (In other words, it's not an executable.) – jpaugh – 2017-04-27T21:58:18.5735@jpaugh: A clearer way to say that is: alias expansion only happens on the first "word" of a command. So as you say, it only works for command names, not args. (And you couldn't even
alias 'cd ,,'='cd ..'
. Well, you could, but you'd have to run it ascd\ ,,
to make it all one word.) – Peter Cordes – 2017-04-28T01:20:46.9275Consider zsh. It has global aliases, so
alias -g ,,=..
andcd ,,
works as you expect it to. – muru – 2017-04-28T05:13:14.187I have this:
function c() { cd "${1-..}"; }
It's just likecd
but the default behavior (when no argument given) is to to the parent directory (instead of the home directory as forcd
). – Lassi – 2017-04-28T06:09:53.5401Lateral thinking:
find / -type d -exec ln -s .. {}/,, \;
... ;-) – Toby Speight – 2017-04-28T12:58:35.673Note that it is possible that there is an actual directory called
,,
(trymkdir ,,
). – Federico Poloni – 2017-04-29T09:57:56.0302Imho: don't do this. Using aliases to cover up typographic errors is a bad practice. Those errors can end up in copy-pasted code or screencasts. It won't work in other hosts or accounts. And such modification (depending on how it's implemented) could cause other, unexpected, difficult to debug errors. My suggestion: if you mistype a command, simply type it again ;-). – jjmontes – 2017-05-01T14:11:52.223