Can I make a custom "directory alias" like '~' in bash?

In bash I can go to my home directory with cd ~ and actually refer to my home directory with any command with ~.

Can I make new, custom "directory aliases" (?) to refer to other directories? Hypothetical example:

make_alias "~~" /mnt/photon/work/foo_project/

cp ~/home.png ~~/set_8/home_4.png

How it can be done, if so? If it cannot, is it by design and why so?

Nice to have: Where and how ~ is set and bound to this "~"?


Solution 1:

The tilde is not an alias, it's part of bash's shell expansion (just like *.txt or $((1 + 2))).

Bash tilde expansion supports the following tilde-prefixes:

~            The value of $HOME

~/foo        $HOME/foo

~fred/foo    The subdirectory foo of the home directory of the user fred

~+/foo       $PWD/foo

~-/foo       ${OLDPWD-'~-'}/foo

~N           The string that would be displayed by `dirs +N'

~+N          The string that would be displayed by `dirs +N'

~-N          The string that would be displayed by `dirs -N'

dirs uses the directory stack. You can use pushd to add a directory to it.

To answer your specific question about ~~, yes, it is possible to map a directory to it. Just create a user called ~ and set /mnt/photon/work/foo_project/ as its home directory:

sudo useradd '~'
sudo sed -i 's#:/home/~:[^:]*$#:/mnt/photon/work/foo_project:/bin/false#' /etc/passwd

Of course, a much "saner" approach is just defining a shell variable that points to your directory in your ~/.bashrc with the command

foo=/mnt/photon/work/foo_project

which can be accessed via $foo, as usual.