我试图模仿Unix命令通过使用Perl是否在Perl符号链接功能覆盖现有的链接
symlink (/path/to/file /path/to/link)
还包括Perl删除现有目标文件
ln -sf /path/to/file /path/to/link
,并创建类似符号链接-s -f选项?
我试图模仿Unix命令通过使用Perl是否在Perl符号链接功能覆盖现有的链接
symlink (/path/to/file /path/to/link)
还包括Perl删除现有目标文件
ln -sf /path/to/file /path/to/link
,并创建类似符号链接-s -f选项?
symlink
只是简单地调用相同名称的OS调用(symlink(2)
),当“newpath
已存在”时返回错误EEXIST
。
如果你想实现-f
,你可以使用
unlink($new_qfn);
symlink($old_qfn, $new_qfn)
or die("Can't create symlink \"$new_qfn\": $!\n");
但是,下列情况处理竞争条件更好的工作:
if (!symlink($old_qfn, $new_qfn)) {
if ($!{EEXIST}) {
unlink($new_qfn)
or die("Can't remove \"$new_qfn\": $!\n");
symlink($old_qfn, $new_qfn)
or die("Can't create symlink \"$new_qfn\": $!\n");
} else {
die("Can't create symlink \"$new_qfn\": $!\n");
}
}
ln
采用后一种方法。
$ strace ln -sf a b
...
symlink("a", "b") = -1 EEXIST (File exists)
unlink("b") = 0
symlink("a", "b") = 0
...
这很容易弄清楚你自己。让我们来试试
ls -li link_to_FILE.txt
# 2415940160 lrwxrwxrwx. ... link_to_FILE.txt -> FILE.txt
与
perl -wE'symlink "FILE.txt", "link_to_FILE.txt" or warn "Cant make it: $!"'
它打印
Cant make it: File exists at -e line 1.
,我检查原始文件(链接)具有相同的inode编号仍然存在。
所以,不,它不会覆盖现有的文件。
symlink的页面表示没有选项f orce那。
这是一个很好的答案。谢谢! – pmsuresh