03. File tests

With file tests, we can check simple properties of file attributes. The file tests that require just one argument are called unary operators.

Existence

There are two simple tests to see if a file exists and if it's empty.

-e
File exists
-s
File is not empty
$ [ -e testFile.txt ]; echo $?
1
$ touch testFile.txt
$ [ -e testFile.txt ]; echo $?
0
$ [ -s testFile.txt ]; echo $?
1 # File is empty
$ echo "Hello world" > testFile.txt
$ [ -s testFile.txt ]; echo $?
0

Type

The following checks for the file's type. If any of the options below are used on a file that doesn't exist, the exit code returns a nonzero value.

-b
Block device
-c
Character device
-d
Directory
-f
Regular file
-L
Symbolic link
-O
Group matches the effective group id of this process
-p
Named pipe
-s
Socket
$ [ -d Downloads ]; echo $?
0
$ touch testFile.txt
$ [ -f testFile.txt ]; echo $?
0

Permissions

We may also check the permissions settings of a file.

-r
Readable
-w
Writable
-x
Executable
-u
uid has been set
-g
gid has been set
-k
Sticky bit is set
$ touch testFile.txt
$ ls -l testFile.txt
-rw-r--r--  1 johnPC  staff  0 Jul  3 11:02 testFile.txt
$ [ -r testFile.txt ]; echo $?
0
$ [ -w testFile.txt ]; echo $?
0
$ [ -x testFile.txt ]; echo $?
1
$ chmod a+x testFile.txt
$ [ -x testFile.txt ]; echo $?
0

Comparisons

Lastly, we have comparison operators, which looks at two files.

[ file1 -nt file2 ]     
-nt
file1 is newer than file2
-ot
file1 is older than file2
-ef
file1 and file2 share inode numbers
$ touch oldFile.txt
$ touch newFile.txt
$ [ oldFile.txt -nt newFile.txt ]; echo $?
1
$ [ oldFile.txt -ot newFile.txt ]; echo $?
0

Great! All this will come in handy once we learn key control-flow commands such as if-else statements and loops.

Take your Linux skills to the next level!

How Linux Works

Take your Linux skills to the next level! Try Linux & UNIX

In this completely revised second edition of the perennial best seller How Linux Works, author Brian Ward makes the concepts behind Linux internals accessible to anyone curious about the inner workings of the operating system. Inside, you'll find the kind of knowledge that normally comes from years of experience doing things the hard way.

$ Check price
39.9539.95Amazon 5 logo(114+ reviews)

More Linux & UNIX resources

Aching back from coding all day?

Foam Seat Cushion

Aching back from coding all day? Try Back Problems

This foam seat cushion relieves lowerback pain, numbness and pressure sores by promoting healthy weight distribution, posture and spine alignment. Furthermore, it reduces pressure on the tailbone and hip bones while sitting. Perfect for sitting on the computer desk for long periods of time.

$ Check price
99.9599.95Amazon 4.5 logo(9,445+ reviews)

More Back Problems resources

Ad