实例:取得符号链接的真实路径

实例:取得符号链接的真实路径

要求:取得符号链接指向的真实文件所在文件夹
要考虑多复链接和相对链接

其实并不简单,当然也不至于复杂:)
[php]
[0 No.2069 huan@huan /tmp/realpath/a]$ cat realpath
#! /bin/bash

abs_path(){
    local path=$1
    local basename=$( basename $path )
    local dirname=$(  dirname  $path )
    cd $dirname
    if [ -h $basename ]; then
        path=$( readlink $basename )
        abs_path $path
    else
        pwd
    fi
}

echo "Bash: $( abs_path $0 )"
exit 0


#! /usr/bin/perl

use Cwd 'abs_path';

my $abs_path = abs_path($0);
$abs_path =~ s![^/]+$!!;

print "erl: ", "$abs_path", "\n";

[0 No.2070 huan@huan /tmp/realpath/a]$ tree
.
|-- b
|   |-- c
|   |   |-- d
|   |   |   `-- realpath
|   |   `-- realpath -> d/realpath
|   `-- realpath -> c/realpath
`-- realpath -> b/realpath

3 directories, 4 files

[0 No.2071 huan@huan /tmp/realpath/a]$ perl realpath
Bash: /tmp/realpath/a/b/c/d

[0 No.2072 huan@huan /tmp/realpath/a]$ perl -x realpath
Perl: /tmp/realpath/a/b/c/d/

[0 No.2073 huan@huan /tmp/realpath/a]$
[/php]      
复制内容到剪贴板
代码:
[color=blue]-(dearvoid@LinuxEden:tty3)-(~/tmp/link)-
[26277 0][/color] [color=red]; l
[/color]total 4
drwxr-xr-x 2 root root 4096 2007-04-06 09:13 a
-rw-r--r-- 1 root root    0 2007-04-06 09:13 b
lrwxrwxrwx 1 root root    3 2007-04-06 09:13 c -> a/b
[color=blue]-(dearvoid@LinuxEden:tty3)-(~/tmp/link)-
[26277 0][/color] [color=red]; l a
[/color]total 0
lrwxrwxrwx 1 root root 4 2007-04-06 09:13 b -> ../b
[color=blue]-(dearvoid@LinuxEden:tty3)-(~/tmp/link)-
[26277 0][/color] [color=red]; readlink c
[/color]a/b
[color=blue]-(dearvoid@LinuxEden:tty3)-(~/tmp/link)-
[26277 0][/color] [color=red]; readlink -f c
[/color]/root/tmp/link/b
[color=blue]-(dearvoid@LinuxEden:tty3)-(~/tmp/link)-
[26277 0][/color] [color=red]; pwd
[/color]/root/tmp/link
[color=blue]-(dearvoid@LinuxEden:tty3)-(~/tmp/link)-
[26277 0][/color] [color=red]; o
[/color]
      
readlink还有这么好的参数...