Can ',,' be aliased to '..'?
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.
ZSH:
If you'r using zsh
alias -g ,,=".."
is what you need, but this will cause ",," to be expanded everywhere, not only when used with cd
.
From man zshbuiltins
:
If the
-g
flag is present, define a global alias; global aliases are expanded even if they do not occur in command position.
BASH:
If restricted to bash
(as the question is tagged with bash), read the following:
This is a pure-alias solution, as requested, however this will do more than required possibly frustrating the user (see the warning at the end of my post).
Quoting man bash
:
If the last character of the alias value is a blank, then the next command word following the alias is also checked for alias expansion.
Therefore it's enough to alias cd
with an extra space (to allow expanding of its next argument) and then alias ,,
to ..
. See that
alias cd='cd '
alias ,,='..'
gives exactly what you need.
Note that this is correct not only for bash
(and its alias
implementation), but all POSIX-compilant shells. Quoting an example from man 1p alias
(the manual does not describe this feature explicitly, only through an example):
Set up nohup so that it can deal with an argument that is itself an alias name:
alias nohup="nohup "
Warning:
As @PeterCordes writes in his comment, it will automatically cause other aliases to expand when written after cd
. It may require you to write cd \grep
if you want to change directory to one named grep
but your grep
is an alias for grep --color=auto
. Without the backslash, cd
will report "too many arguments" error (you can't cd
to two directories at once)!.
Aliases must be the first word of a command. Also, the alias must be substituted for a word therefore no spaces).
Bash Reference Manual: Aliases
Aliases allow a string to be substituted for a word when it is used as the first word of a simple command.
You could alias both ..
and ,,
to be cd ..
.
$ alias ..="cd .."
$ alias ,,="cd .."
$ cd /tmp && pwd
/tmp
$ ,, && pwd
/