Test Function

The Bash Test Function...


   [ + space + expression + space + ]

Test is used to check out a string, number or a file. The only output of test is it's exit status. If it returns 0 the test is sucessful, any other number is a failure.

The syntax comes in two forms:

  • test expression
  • [ expression ]

The spaces between the expression and the brackets are required.

CREATED 2012-11-17 03:32:48.0

00-17-C7

UPDATED 2012-11-18 18:12:29.0

Test Options...


Examples follow but first a list of common test options:

-d file True if <file> is a directory
-e file True if <file> exists
-f file True if <file> exists and is a file
-h file True if <file> exists and is a symbolik link
-L file True is <file> is a symbolic link
-r file True is <file> is readable by you (the current user)
-w file True if <file> is writable by you
-x file True if <file> is executable by you
file1 -nt file2 True if <file1> is newer than <file2>
file1 -ot file2 True if <file1> is older than <file2>
-z string True if <string> is empty
-n string True if <string> is not empty
string1 = string2 True if <string1> equals <string2>
string1 != string2 True if <string1> is not equal to <string2>

CREATED 2017-04-11 03:57:13.0

00-29-90

UPDATED 2017-04-11 03:57:22.0

Examples


then

The -f flag tests for the existance of a file. Remember there are two ways of executing a test. [ <option> <arg>]. (Don't forget the spaces around the brackets)

if [ -f myfile.txt ]

CREATED 2012-11-18 18:21:33.0

00-17-E4

UPDATED 2017-04-11 04:38:09.0

Logicel AND and OR...


The && (logical AND) and || (logical OR) can be used to string two test cases together in a single statement:

if [ -f "$myfile" ] && [ -r "$myfile" ]
then
   <write to file>
fi

However later versions of test offer two other options -a for AND and -o for OR:

if [ -f "$myfile" -a -r "$myfile" ]
then
   <write to file>
fi

Both of these do the same thing. However, && and || operate at the shell level where -a and -o operate within the test command. Also -a and -i don't short circut.

CREATED 2017-04-11 04:48:58.0

00-29-91

UPDATED 2017-04-11 04:49:10.0

Knowledge

L
I
N
K
S

DBID: db.wam

Page Server: Ruger

©2012 Leistware Data Systems

      Hello anonymous