8

I want to create a one way symlink i.e. I can use it to go to the destination directory but I cannot go back.

Let's say there is a directory called D with two subdirectories S1 and S2. I want to create a link in S1 that points to S2 (let's say ls2 -> ../S2/). If I do cd ls2 and then cd .. then I want to go to D and not S1.

Is it possible?

1
  • 7
    All symlinks are unidirectional... The ability to go back depends on whether you remember from where you came. So shells do remembers, others don't. Many shells won't remember when you use cd -P to change directory.
    – AlexP
    Oct 16, 2019 at 13:17

1 Answer 1

21

All symbolic links are one-way. As far as the kernel is concerned, after going into /D/S1 and running chdir("ls2"), you're in /D/S2, so if you run chdir(".."), you end up in /D.

If you do this in a shell, after

cd /D/S1
cd ls2
cd ..

you end up in /D/S1. The reason is that the shell does its own tracking of the current directory, and it remembers symbolic links.

You can't disable this shell behavior on a link-by-link basis, but you can disable it when you run the cd command. After running cd ls2, the shell remembers the current directory as /D/S1/ls2:

$ pwd
/D/S1
$ cd ls2
$ pwd
/D/S1/ls2
$ cd ..
$ pwd
/D/S1

To instruct the shell to forget its symlink-aware current directory tracking, pass the -P option to cd. The pwd command also has a -P option.

$ pwd
/D/S1
$ cd ls2
$ pwd
/D/S1/ls2
$ pwd -P
/D/S2
$ cd -P ..
$ pwd
/D

You can also forget the logical tracking when you change into the symlink:

$ pwd
/D/S1
$ cd -P ls2
$ pwd
/D/S2
$ cd ..
$ pwd
/D
2
  • A small additional question if it is fine. Is there a way to make the file browser (thunar) forget the symlink track?
    – WYSIWYG
    Oct 31, 2019 at 12:29
  • @WYSIWYG I have no idea. You should ask that separately in a question tagged thunar. Oct 31, 2019 at 12:54

You must log in to answer this question.

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