We check traits for the files quite often. We want to find out if a file exists, if we have the right to delete it or even if there is a valid, executable file. These tasks become simple with the syntaxes I am going to show you. The only question is what the syntax of the expression is. After this, you can replace that with either of the syntaxes of the test presented on the previous page. For the file it can be:
Expression
Test checks for what trait?
-d file
True if the file exists and it is a directory (d)
-e file
True if the file exists (e)
-f file
True if the file exists and is a regular file (f)
-L file
True if the file exists and it is a symbolic link (L)
-r file
True if the file exists and you can read (r) it
-s file
True if the file exists and its size (s) is greater than zero
-w file
True if the file exists and you can write (w) to it
-x file
True if the file exists and you can execute (x) it
-O file
True if the file exists and it its owner (O) is the actual user
-G file
True if the file exits and its owner is in your group (g)
File1 -nt file2
True if File1 is newer than (nt) file2 (from the point of view of the access time)
File1 -ot file2
True if File1 is older than (ot) file2
File1 -ef file2
True if the two files are equal files (ef). For this, the i-node and device numbers must be the same.
A couple of examples:
#check if we can run the first argument of a shell script
if test -x $1
then
echo " We can and will start the program"
bash $1
fi
#if alfa.txt exists and we can delete it, remove it
if [ -e alfa.txt ] && [ -w alfa.txt ]
then
rm alfa.txt
else
echo "The file does not exists or no right to delete it"
fi
Then again, there we have the expressions related to strings.
Expression
Test checks for what trait?
-z string
True if the string has a length equal to zero (z)
-n string
True if the length of the string is not (n) zero
string1 = string2
True if the strings are the same
string1 != string2
True if the strings differ
The usage of this is just as simple. Let us consider the following script snippets, where the $1 is the first argument of the script:
if test -z alfa
then
echo The variables alfa has a length equal with zero