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!

Command Line Kung Fu

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

Command Line Kung Fu is packed with dozens of tips and practical real-world examples. You won't find theoretical examples in this book. The examples demonstrate how to solve actual problems. The tactics are easy to find, too. Each chapter covers a specific topic and groups related tips and examples together.

$ Check price
14.9914.99Amazon 4.5 logo(27+ reviews)

More Linux & UNIX resources

Aching back from coding all day?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ reviews)

More Back Problems resources

Ad