ERRNO

The ERRNO variable stores the error message as a string if the redirection (I/O) operation fails while using the getline command. These errors happen mostly while performing read operations or during a close operation. GAWK clears the ERRNO before opening each command-line input file.

We will be using AWK's built-in getline command to read the input from the file to understand how the ERRNO variable works. The getline command returns 1 if it finds a record and 0 if it encounters the end of file. If an error occurs when it is getting the record, for example if the file could not be read or found, then it returns -1. In this scenario, GAWK will set ERRNO to a string explaining the error.

For example, let's create the following AWK script to check whether the employee's first name is Eva, and to make getline read from dummy-file.txt if the employee with this first name is found. As, there is no such file, ERRNO will store the error message, which is displayed using a print statement, as follows:

$ vi erro.awk

{
x=getline < "dummy-file.txt"
if ($1 == "Eva")
{
print "Trying to read from file : dummy-file.txt"
if ( x == -1 )
print ERRNO
else
print $0;
}
}

$ awk -f err.awk emp.dat

The output of the execution of the preceding code is as follows:

Trying to read from file : dummy-file.txt
No such file or directory
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.194.170