Nandakumar Edamana
Share on:
@ R t f

Shell Script to Utilize File Test Operators


The following script makes use of the file test operators provided by the test command (actually, its shortcut []) to get some information regarding the files recommended by the user.

Please note that test uses the term file for both files and directories (folders) in many cases.

Code

Updated on Apr 4, 2017, 7:31 PM IST: filename variables used in the test expressions are now given inside double quotes to avoid issues caused by white spaces or other special characters.

#!/bin/sh

echo "FILE TEST OPERATORS FOR A SINGLE FILE"
echo "=====================================\n"

echo "Enter a filename: "
read filename

echo -n "\nWhether the file is existing: "
if [ -e "$filename" ]; then
	echo "Yes"

	echo -n "Whether the file is a file: "
	if [ -f "$filename" ]; then
		echo "Yes"
	else
		echo "No"
	fi

	echo -n "Whether the file is a directory: "
	if [ -d "$filename" ]; then
		echo "Yes"
	else
		echo "No"
	fi

	echo -n "Has read permission: "
	if [ -r "$filename" ]; then
		echo "Yes"
	else
		echo "No"
	fi

	echo -n "Has write permission: "
	if [ -w "$filename" ]; then
		echo "Yes"
	else
		echo "No"
	fi

	echo -n "Has execution permission: "
	if [ -x "$filename" ]; then
		echo "Yes"
	else
		echo "No"
	fi
else
	echo "No. Skipping single file tests."
fi

echo "\nFILE TEST OPERATORS FOR TWO FILES"
echo "=================================\n"

echo "Enter filename1: "
read filename1

echo "Enter filename2: "
read filename2

if [ ! -e "$filename1" ] || [ ! -e "$filename2" ] ; then
	echo "\nBoth files should exist before they can be compared."
else # Both files exist
	if [ "$filename1" -nt "$filename2" ]; then
		echo "\n$filename1 is newer than $filename2"
	else
		echo "$filename1 is older than $filename2"
	fi
fi

The code is self explanatory. -e tests whether the file (or folder) is existing. -f tests whether the filename represents a directory (i.e., folder). The code goes on like this.


Keywords (click to browse): file-test-operators files directories folders test shell sh bash linux gnu unix script programming command-line