0
0
Bash Scriptingscripting~5 mins

File test operators (-f, -d, -e, -r, -w, -x) in Bash Scripting

Choose your learning style9 modes available
Introduction

File test operators help you check different properties of files or directories in scripts. This lets your script make decisions based on file types or permissions.

Check if a file exists before reading it.
Verify if a directory exists before saving files there.
Confirm if a file is writable before trying to write data.
Ensure a script file is executable before running it.
Test if a file is a regular file or a directory.
Syntax
Bash Scripting
[ -f filename ]  # True if filename is a regular file
[ -d filename ]  # True if filename is a directory
[ -e filename ]  # True if filename exists
[ -r filename ]  # True if filename is readable
[ -w filename ]  # True if filename is writable
[ -x filename ]  # True if filename is executable

Use these inside square brackets with spaces around them.

They return true or false and are often used in if statements.

Examples
This checks if 'myfile.txt' is a regular file and prints a message if true.
Bash Scripting
if [ -f myfile.txt ]; then
  echo "myfile.txt is a regular file"
fi
This checks if 'myfolder' exists and is a directory.
Bash Scripting
if [ -d myfolder ]; then
  echo "myfolder is a directory"
fi
This checks if 'myfile.txt' has read permission.
Bash Scripting
if [ -r myfile.txt ]; then
  echo "You can read myfile.txt"
fi
This checks if 'script.sh' can be run as a program.
Bash Scripting
if [ -x script.sh ]; then
  echo "script.sh is executable"
fi
Sample Program

This script checks if 'example.txt' exists. If yes, it tells what type it is and what permissions it has.

Bash Scripting
#!/bin/bash
filename="example.txt"

if [ -e "$filename" ]; then
  echo "$filename exists."
  if [ -f "$filename" ]; then
    echo "$filename is a regular file."
  elif [ -d "$filename" ]; then
    echo "$filename is a directory."
  fi
  if [ -r "$filename" ]; then
    echo "$filename is readable."
  else
    echo "$filename is not readable."
  fi
  if [ -w "$filename" ]; then
    echo "$filename is writable."
  else
    echo "$filename is not writable."
  fi
  if [ -x "$filename" ]; then
    echo "$filename is executable."
  else
    echo "$filename is not executable."
  fi
else
  echo "$filename does not exist."
fi
OutputSuccess
Important Notes

Always quote filenames to handle spaces or special characters.

These tests are case-sensitive and depend on the file system.

Use these operators to avoid errors when accessing files in scripts.

Summary

File test operators check file existence, type, and permissions.

They are used inside if statements to control script flow.

Common operators: -f (file), -d (directory), -e (exists), -r (readable), -w (writable), -x (executable).