0
0
Bash Scriptingscripting~20 mins

File test operators (-f, -d, -e, -r, -w, -x) in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Check File Properties Using File Test Operators in Bash
📖 Scenario: You are managing files on your computer. Sometimes you need to check if a file exists, if it is a regular file or a directory, and if you have permission to read, write, or execute it.In this project, you will write a bash script that uses file test operators to check these properties for a given file path.
🎯 Goal: Build a bash script that checks if a file exists, if it is a regular file or directory, and if it has read, write, and execute permissions. Then print the results clearly.
📋 What You'll Learn
Create a variable with a file path
Create a variable to hold a message prefix
Use file test operators: -e, -f, -d, -r, -w, -x
Print messages showing the file's properties
💡 Why This Matters
🌍 Real World
System administrators and developers often need to check file properties before running scripts or commands to avoid errors.
💼 Career
Knowing how to use file test operators in bash is essential for writing safe and effective shell scripts in IT and DevOps roles.
Progress0 / 4 steps
1
Create a variable with the file path
Create a variable called file_path and set it to "/tmp/testfile.txt".
Bash Scripting
Need a hint?

Use the syntax variable_name="value" to create a variable in bash.

2
Create a message prefix variable
Create a variable called msg and set it to "Checking file: $file_path" using double quotes and the variable file_path.
Bash Scripting
Need a hint?

Use double quotes to include variables inside strings in bash.

3
Use file test operators to check file properties
Write if statements using the file test operators -e, -f, -d, -r, -w, and -x to check if file_path exists, is a regular file, is a directory, is readable, writable, and executable. For each check, set a variable named exists, is_file, is_dir, can_read, can_write, and can_exec to true or false accordingly.
Bash Scripting
Need a hint?

Use if [ -e "$file_path" ] to check if a file exists. Use similar syntax for other tests.

4
Print the results
Print the message stored in msg. Then print each property with a clear message, for example: echo "Exists: $exists", echo "Is regular file: $is_file", and so on for all variables exists, is_file, is_dir, can_read, can_write, and can_exec.
Bash Scripting
Need a hint?

Use echo to print messages. Print the msg variable first, then each property variable with a label.