Tuesday 10 January 2017

Common file test operations in Perl

Performing an action based on the existence or contents of a file or directory is fairly common in shell scripting. In this article, we explore some of the tests that we can run against a file/directory using the if conditional statement.

1. Check for existence of file (-e).

The following little program checks if a file named testfile exists & prints the name else it prints the error message stored in $! variable.

#!/usr/bin/perl -w
#
use strict ;

my $file_name = "/root/testfile";

if (-e $file_name) {
        print "file name is $file_name \n" ;
}
else {
        print "$file_name $! \n" ;
}

When we execute the script we get the following result:

[root@alive ~]# ./filetest.pl
file name is /root/testfile

Now if I change the file name to testfile1, the output changes.

[root@alive ~]# ./filetest.pl
/root/testfile1 No such file or directory


2. Check if file is writable (-w).


3. Check if file is empty (-z):

The file testfile is not empty, so if I run the following script:

#!/usr/bin/perl -w
#
use strict ;

my $file_name = "/root/testfile";

if (-z $file_name) {
        print "file name is $file_name \n" ;
}
else {
        print "$file_name not empty $! \n" ;
}

I'll get this result:

[root@alive ~]# ./filetest.pl
/root/testfile not empty
[root@alive ~]#

We can run negate tests as well, For example if I wanted a true result from if statement if the file was not empty, I could precede -z by not to indicate a negative match as shown below:

#!/usr/bin/perl -w
#
use strict ;

my $file_name = "/root/testfile";

if (not -z $file_name) {
        print "file name is $file_name \n" ;
}
else {
        print "$file_name not empty $! \n" ;

The result of this scripts' execution would be:

[root@alive ~]# ./filetest.pl
file name is /root/testfile


4. Check if the file is a plain text file (-f).
This will check if the file is a text file or a special file like a device file or an executable file.


5. Check that the file exists and is of non-zero size (-s).
This can be regarded as somewhat the opposite of the -z option.


6. Check if the file is a directory (-d).


There are many more file test operations available which can be looked up from perldoc. 

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...