Saturday 20 October 2018

File Test Operators / Operations Examples in Unix / Linux Shell Script

In linux and unix operating systems every thing is a file. When you are using files in your shell or bash script, it is a good idea to do some tests on the file before using it.

LPI Certification, LPI Guides, LPI Learning, LPI Study Materials, LPI Tutorial and Material

The file tests include:

◈ Checking for existence of the file.
◈ File is readable, writeable or executable.
◈ Type of the file and so on.

The file test operators are mostly used in the if clause of the bash script. The syntax is shown below:

if [ -option filename ]
then
  do something
else
  do something
fi

The different file test operators are listed below:

◈ a : True if the file exists.
◈ b : True if the file exists and is a block special file.
◈ c : True if the file exists and is a character special file.
◈ d : True if the file exists and is a directory.
◈ e : True if the file exists.
◈ f : True if the file exists and is a regular file.
◈ g : True if the file exists and its SGID bit is set.
◈ h : True if the file exists and is a symbolic link.
◈ k : True if the file exists and its sticky bit is set.
◈ p : True if the file exists and is a named pipe (FIFO).
◈ r : True if the file exists and is readable.
◈ s : True if the file exists and has a size greater than zero.
◈ t : True if file descriptor is open and refers to a terminal.
◈ u : True if the file exists and its SUID (set user ID) bit is set.
◈ w : True if the file exists and is writable.
◈ x : True if the file exists and is executable.
◈ O : True if the file exists and is owned by the effective user ID.
◈ G : True if the file exists and is owned by the effective group ID.
◈ L : True if the file exists and is a symbolic link.
◈ N : True if the file exists and has been modified since it was last read.
◈ S : True if the file exists and is a socket.

File Test Operator Example:


The following shell script checks for the existence of a regular file:

#!/bin/bash
#assign file name to the variable
FILE="linux-server.dat"

if [ -f $FILE ]
then
  echo "$FILE exists and is a regular file"
else
  echo "Either $FILE does not exist or is not a regular file"
fi 

Related Posts

0 comments:

Post a Comment