So let's say I have a symbolic link of a file in my home directory to another file on a different partition. How would I find the target location of the linked file? By this, I mean, let's say I have file2
in /home/user/
; but it's a symbolic link to another file1
. How would I find file1
without manually having to go through each partition/directory to find the file?
5 Answers
Use readlink:
readlink -f /path/file
( last target of your symlink if there's more than one level )
If you just want the next level of symbolic link, use:
readlink /path/file
You can also use realpath on modern systems with GNU coreutils (e.g. Linux), FreeBSD, NetBSD, OpenBSD or DragonFly:
realpath /path/file
which is similar to readlink -f
.
1.
ls -l bin
produce
lrwxrwxrwx 1 az az 14 Ноя 12 22:13 bin -> ../Gdrive/bin/
2.
file bin
produce
bin: symbolic link to `../Gdrive/bin/'
3.
stat bin
produce
File: «bin» -> «../Gdrive/bin/»
-
ok well im trying to make a script, so how would i use these? im new to linux.– k-RockerNov 12, 2014 at 20:21
-
2
Simplest way: cd
to where the symbolic link is located and do ls -l
to list the details of the files.
The part to the right of ->
after the symbolic link is the destination to which it is pointing.
Ex:
lrwxrwxrwx 1 userName groupName 22 Jan 17 13:29 Link to temp.txt -> /home/user/temp.txt
Here we have "Link to temp.txt" that points to (->
) "/home/user/temp.txt".
But, like @Gilles Quenot points out, you can also just do readlink -f /path/to/symbolic_link
Expanding on Costas
Suppose you have
ln -s test.txt sym_link_1.txt
ls -l sym_link_1.txt
lrwxrwxrwx. 1 a1 g1 8 Jan 7 16:59 sym_link_1.txt -> test.txt
In a script you can do (use backticks)
ln -s `readlink sym_link_1.txt` sym_link_2.txt
Then you have
ls -l sym_link_*.txt
lrwxrwxrwx. 1 a1 g1 8 Jan 7 16:59 sym_link_1.txt -> test.txt
lrwxrwxrwx. 1 a1 g1 8 Jan 7 17:01 sym_link_2.txt -> test.txt
Another method (which are not answered previously) to find link files is to use the below command,
file -h <path_to_dir>/* | grep link
Command:
file -h /home/prateek/* | grep link
Output:
/home/prateek/Music: symbolic link to /media/prateek/HD-E1/Music
file1
is a symlink tofile0
? Do you want to find the last target of your symlink (file0
) or just the next one (file1
) ?