Softpanorama
(slightly skeptical) Open Source Software Educational Society

May the source be with you, but remember the KISS principle ;-)

Softpanorama Search

Introduction to Perl for Unix System Administrators

(Perl without excessive complexity)

by Dr Nikolai Bezroukov


4.2. Determining the Status of a File

Files Predicates

As you have seen, when you open a file for writing, the existing contents of the file are destroyed. There are several dozens operators in Perl that can help to test  the status of the file. The most widely used are just file listed in the table below:

 File status operators.

Operator File condition
-d Is this a directory?
-e Does this file exist?
-r Is this file readable by the person running the script?
-s Returns the size of the file
-w Is this file writeable by the person running the script?
-x Is this file executable by the person running the script?

First we will discuss probably the most popular test among listed above the -e test. If you want to open the file for writing if the file does not already exist, you can first test to see if a file exists using the -e operator.

All other file-test operators have the same syntax as the -e operator used below. This is a unary operator that accept string as its only operand. The value of the string should contain the name of the file to be tested. It can be fully qualified name or relative name.

unless (-e "/home/nnb/.profile") {
        die ("file /home/nnb/.profile does not exist");
}
open (SYSPROF, "/home/nnb/.profile");

If the file exists, the -e operator returns true; otherwise, it returns false. Similar tests exist to test other file conditions. Here is another example:

 unless (open(SYSIN, "c:/windows/win.ini" {

          if (-e "c:/windows/win.ini") {

                 die ("File  c:\\windows\\win.ini exists, but cannot be opened.\n"));

          } else {

                 die ("File c:\\windows\\win.ini does not exist.\n");

         }

If you use Windows and need specify full path using backslashes, please remember that they need to be doubles as backslash serves as a escape character in Perl literals. Actually you can use regular slash, but this is convenient solution only for people who get used to Unix.

You can even extend previous trick with | | operator, but it becomes somewhat less comprehensible and although this is a Perl idiom this is a bad Perl idiom -- I recommend against using it:

open(SYSIN, "infile") && !(-e "infile") || die("Cannot open infile\n");

In Unix and Windows NT (unless you are always using root and administrator IDs to login ;-) before you can open a file for reading, you must have permission to read the file. The -r file-test operator tests whether you have permission to read a file.

$fname="testfile";

unless (open(SYSIN, "$fname")) {

  if (!(-e "file1")) {die ("File $fname does not exist.\n");}

  unless (-r "file1")) {die ("You are not allowed to read $fname.\n");

  die ("File1 cannot be opened. Reason unknown\n");

}

 To check whether you have write permission on a file, use the -w file-test operator.

unless (-w "$fname") {

        print STDERR ("Can't write to $fname.\n");

}

The -x file-test operator is used mainly in Unix environment and it checks whether you have execute permission on the file (in other words, whether the system thinks this is an executable script, and whether you have permission to run it if it is), as illustrated here:

unless (-x "$fname") {

        print STDERR ("I can run $fname.\n");
}

The -s file-test operator, which returns the size of the file in bytes. This provides a more refined test for whether or not to open a file for writing: if the file exists but is empty, no information is lost if you overwrite the existing file.

$size = -s "outfile";

if ($size == 0) {

        print ("The file is empty.\n");

} else {

        print ("The file is $size bytes long.\n");

}

The file-test operators provide a way of retrieving information on a particular file. The most common file-test operators are

Full list of file test operators contain more than a dozen entries as shown in the table below:

Operator Description
-b Is filename a block device?
-c Is filename a character device?
-d Is name a directory?
-e Does filename exist?
-f Is filename an ordinary file?
-g Does filename have its setgid bit set?
-k Does filename have its "sticky bit" set?
-l Is filename a symbolic link?
-o Is filename owned by the user?
-p Is name a named pipe?
-r Is filename a readable file?
-s Returns the size of the file
-t Does name represent a terminal?
-u Does filename have its setuid bit set? The effective userid in this case will be different fromt the user login ID
-w Is filename a writable file?
-x Is filename an executable file?
-z Is filename an empty file?
-A How long since filename accessed?
-B Is filename a binary file?
-C How long since filename's inode accessed?
-M How long since filename modified?
-O Is filename owned by the "real user" only? (See -u (setuid bit) comment)
-R Is filename readable by the "real user" only? (See -u (setuid bit) comment)
-S Is name a socket?
-T Is filename a text file?
-W Is filename writable by the "real user" only? (See -u (setuid bit) comment)
-X Is filename executable by the "real user" only? (See -u (setuid bit) comment)

stat function

The stat function accepts a filehandle or the name of the file. It returns a 13-element list giving the status info for a file. If name of the file is specified it can be iether fully qulified or relative name. If no arguments are suppiled $_ is used as a default argument. The function returns an empty list in case of failure. Typically used as follows:
    ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
       $atime,$mtime,$ctime,$blksize,$blocks)
           = stat($filename);

Not all fields are supported on all filesystem types. Here are the meaning of the fields: 

  0 dev      device number of filesystem
  1 ino      inode number
  2 mode     file mode  (type and permissions). The result is in octal form and contains 
             five digits
  3 nlink    number of (hard) links to the file
  4 uid      numeric user ID of file's owner
  5 gid      numeric group ID of file's owner
  6 rdev     the device identifier (special files only)
  7 size     total size of file, in bytes
  8 atime    last access time since the epoch
  9 mtime    last modify time since the epoch
 10 ctime    inode change time (NOT creation time!) since the epoch
 11 blksize  preferred block size for file system I/O
 12 blocks   actual number of blocks allocated 

If stat is passed the special filehandle consisting of an underline, no stat is done, but the current contents of the stat structure from the last stat or filetest are returned. Example:

    if (-x $file && (($d) = stat(_)) && $d < 0) {
        print "$file is executable NFS file\n";
    }

(This works on machines only for which the device number is negative under NFS.)

In scalar context, stat() returns a boolean value indicating success or failure, and, if successful, sets the information associated with the special filehandle _.



Copyright © 1996-2009 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. Submit comments This document is an industrial compilation designed and created exclusively for educational use and is placed under the copyright of the Open Content License(OPL). Site uses AdSense so you need to be aware of Google privacy policy. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

Disclaimer:

Created: November 7 1998; Last modified: September 05, 2009