With file tests, we can check simple properties of file attributes. The file tests that require just one argument are called unary operators.
There are two simple tests to see if a file exists and if it's 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
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.
$ [ -d Downloads ]; echo $? 0 $ touch testFile.txt $ [ -f testFile.txt ]; echo $? 0
We may also check the permissions settings of a file.
$ 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
Lastly, we have comparison operators, which looks at two files.
[ file1 -nt file2 ]
$ 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.
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
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