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.

Aching back from coding all day?

Inversion Therapy Table

Aching back from coding all day? Try Back Problems

Stretch out your back and relieve your back muscles with inversion therapy. This device counteracts the forces of gravity on the body by decompressing and elongating the spine. By using this product just ten minutes a day, you can be well on your way to improved circulation and posture while relieving muscle aches, back pain and stress.

$$ Check price
119.98119.98Amazon 4.5 logo(1,700+ reviews)

More Back Problems resources

Take your Linux skills to the next level!

The Linux Command Line

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

The Linux Command Line takes you from your very first terminal keystrokes to writing full programs in Bash, the most popular Linux shell. Along the way you'll learn the timeless skills handed down by generations of gray-bearded, mouse-shunning gurus: file navigation, environment configuration, command chaining, pattern matching with regular expressions, and more.

$ Check price
39.9539.95Amazon 4.5 logo(274+ reviews)

More Linux & UNIX resources

Ad