13

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 "~"?

4
  • 1
    Not particularly helpful to you, but you can do that with global aliases in.... ZSH, but not BASH. : alias -g ~~='/mnt/photon/work/foo_project/'
    – SuperMagic
    Mar 14, 2013 at 12:06
  • 1
    @SuperMagic: I like global aliases, too. But in the second example (cp ~~/set...) they will fail. Named directories are more appropriate: n=/mnt/photon/work/foo_project and then cp foo ~n/bar. (Note for the OP: Also limited to zsh).
    – mpy
    Mar 14, 2013 at 12:15
  • 1
    @OliverSalzburg: I don't think this is a duplicate. The other question asks about single character remappings (@ or _), which isn't possible in bash, while ~~ certainly is (hacky, but possible). Also, it doesn't answer how this remapping is done.
    – Dennis
    Mar 14, 2013 at 12:17
  • The related question was: superuser.com/questions/541767
    – n611x007
    Mar 14, 2013 at 12:56

1 Answer 1

26

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .