This tutorial will guide you on how to check certain properties of a file such as its existence and permissions using the 'test' command in shell scripting.
By the end of this tutorial, you will be able to:
- Understand what the 'test' command is and how to use it
- Check if a file exists
- Check the permissions of a file
- Write scripts that can make decisions based on file properties
Prerequisites:
- Basic knowledge of Shell scripting
- A Linux or Unix-like operating system
The test command in Unix evaluates the expression parameter. It is often used in condition testing, that's why it's often found in 'if' and 'while' conditional statements.
Syntax: test EXPRESSION
Let's dive into the different ways we can use the test command.
You can use -e
or -f
flag to check if a file exists.
Example:
test -f /path/to/file && echo "File exists" || echo "File does not exist"
You can use -r
, -w
, and -x
to check if a file is readable, writable, and executable respectively.
Example:
test -r /path/to/file && echo "File is readable" || echo "File is not readable"
Example 1: Checking if a file exists
# Check if file.txt exists
if test -f /home/user/file.txt
then
echo "file exists"
else
echo "file does not exist"
fi
Expected output: "file exists" if the file exists, "file does not exist" otherwise.
Example 2: Checking if a file is readable
# Check if file.txt is readable
if test -r /home/user/file.txt
then
echo "file is readable"
else
echo "file is not readable"
fi
Expected output: "file is readable" if the file is readable, "file is not readable" otherwise.
In this tutorial, we've covered how to check file properties using the 'test' command in shell scripting. We've learned how to check if a file exists and how to check a file's permissions.
Next, you could learn more about shell scripting and how to write more complex scripts. You can refer to this guide for more information.
Exercise 1: Write a script that checks if a file is writable.
Exercise 2: Write a script that checks if a file is executable.
Solutions:
Solution 1:
# Check if file.txt is writable
if test -w /home/user/file.txt
then
echo "file is writable"
else
echo "file is not writable"
fi
Solution 2:
# Check if file.txt is executable
if test -x /home/user/file.txt
then
echo "file is executable"
else
echo "file is not executable"
fi
Keep practicing with different file properties and different files to become more comfortable with the 'test' command.