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?
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?
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.
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.
$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 01 '14 at 09:48
"$PWD" still have the old value if current direcory is moved. PWD only set when you cd or initialize by the shell.
– cuonglm
Aug 01 '14 at 10:22
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 01 '14 at 10:35
. and pwd don't have the same value. Imagine that your are in /tmp/ttt. Now if someone try mv ../ttt ../tttt. PWD now still /tmp/ttt. Then you type ln -s "$(pwd)" ~/link. Then ls -l ~/link ==> broken symlink here.
– cuonglm
Aug 01 '14 at 11:21
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 01 '14 at 11:36
-P, the only thing that worked for me in a WD directory that was already a symlink.
– Patrick M
Jan 12 '16 at 16:30
"$PWD"in POSIX shells and~0inzsh. – Stéphane Chazelas Aug 01 '14 at 09:41