Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check and delete a symlink if it exists, using Perl?

Tags:

perl

if (-e "$ENV{MYHOME}/link") {
    system("rm $ENV{MYHOME}/link");
}

This is the code being used to check if a symlink exists and remove it if it does.

I am tracking a bug where this code does not work. I have not been able to figure it out as of now, but what is happening is that this code is unable to remove the symlink, which results in a 'File exists' error down the line.

I wanted to check if there is some fundamental flaw with this technique? I also read about http://perldoc.perl.org/functions/unlink.html but would like to know if the current approach is not recommended due to some reason?

like image 970
Lazer Avatar asked Jan 31 '12 03:01

Lazer


People also ask

How do I delete a symbolic link?

Remove a Symbolic Link using the rm command You can also use the -i flag with the rm command to prompt for confirmation. After that, you can use the ls -l command to confirm if the symlink has been removed. That is all there is to it!

When source is deleted What happens to the symlink on the file?

If a symbolic link is deleted, its target remains unaffected. If a symbolic link points to a target, and sometime later that target is moved, renamed or deleted, the symbolic link is not automatically updated or deleted, but continues to exist and still points to the old target, now a non-existing location or file.

What is symlink in Perl?

Creates a new filename symbolically linked to the old filename. Returns 1 for success, 0 otherwise.


1 Answers

Just use:

if ( -l "$ENV{MYHOME}/link" ) {
    unlink "$ENV{MYHOME}/link"
        or die "Failed to remove file $ENV{MYHOME}/link: $!\n";
}

If the unlink fails, it'll say why. The -l asks if the target is a link. The -e asks if the file exists. If your link is to a non-existent file, it'll return false, and your code would fail to remove the link.

like image 160
unpythonic Avatar answered Oct 22 '22 05:10

unpythonic