File Tests

In system shell scripts, you will often see a test for the existence of a file. If the file exists, then the script may, for example, source it, delete it, rename it, or rewrite it in some way.

To test for the existence of a file with a given name, do the following:

then echo "found lost masterpiece"

else echo "a cultural tragedy for the whole of humanity"

Note how the if has to be closed with fi. Note also that you need a space after the square bracket and before the -f file test.

There are many different file tests including -e (simple existence of a file), -f (existence of a regular file rather than a directory or device file), and -d (a directory), as well as tests based on permissions and modification dates, among others.

You can see examples of these in the standard .profile on SUSE, which contains these lines (commented out as it happens):

/usr/bin/fortune echo fi

These lines cause the fortune program to run when you log in if it is installed. The test -x checks whether the current user has execute permission on / usr/bin/fortune. (If you don't have it installed, you might enjoy trying it out.)

As another example, in /etc/init.d/xntpd,you see these lines:

NTP_CONF="/etc/ntp.conf" if [ ! -f ${NTP_CONF} ]; then echo -n "Time server configuration file, ${NTP_CONF} does not exist."

In other words, if you find that the required file is not there, you output a statement to that effect.

Was this article helpful?

0 0

Post a comment