12

I am now under a directory with very long path. For future visiting it quicker, I would like to create a link to it.

I tried

ln -s . ~/mylink

~/mylink actually links to ~. So can I expand ~ into the obsolute pathname, and then give it to ln?

19

A symlink actually stores the path you give literally, as a string¹. That means your link ~/mylink contains "." (one character). When you access the link, that path is interpreted relative to where the link is, rather than where you were when you made the link.

Instead, you can store the actual path you want in the link:

ln -s "$(pwd)" ~/mylink

using command substitution to put the output of pwd (the working directory name) into your command line. ln sees the full path and stores it into your symlink, which will then point to the right place.

¹ More or less.

|improve this answer|||||
  • 2
    See also "$PWD" in POSIX shells and ~0 in zsh. – Stéphane Chazelas Aug 1 '14 at 9:41
7

You should use:

ln -s "$(cd . && pwd)" ~/mylink

or:

ln -s "$(pwd -P)" ~/mylink

to get the right result for current working directory. It can be changed while you was working in it as in this question.

|improve this answer|||||
  • 1
    The first one will not necessarily help in all shells (see this answer). The OP likely wants to use $PWD (the path he used to get there), rather than $(pwd -P) (the canonical path to the current directory). If $PWD no longer points to the current directory, then there's no saying that $(pwd -P) will in the next minute either. – Stéphane Chazelas Aug 1 '14 at 9:48
  • @StéphaneChazelas: See this unix.stackexchange.com/questions/147693/… – cuonglm Aug 1 '14 at 9:49
  • @StéphaneChazelas: You can see "$PWD" still have the old value if current direcory is moved. PWD only set when you cd or initialize by the shell. – cuonglm Aug 1 '14 at 10:22
  • But what I'm saying is that the OP is as likely to want the old $PWD than some absolute path to the current working directory and that in several shells (ksh93, ash, yash), as explained there calling cd is not guaranteed to make $PWD or the output of pwd a path to the current directory. You're trying to guard against something that is not likely to happen, but in the first solution, that's not necessarily effective, and in the second, that's changing the behaviour. – Stéphane Chazelas Aug 1 '14 at 10:35
  • 1
    If someone does the mv after you do ln, then you end up in the same situation. On the other hand, if he did cd /long/logical/path/to/some/directory, you don't want the link to point to /vg0/lv1/user2/app4 (the canonical path) as the link will point to the wrong place when /long/logical/path/to/some/directory points to somewhere else. – Stéphane Chazelas Aug 1 '14 at 11:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.