Checking File Types and Permissions

Su Suriya Ravichandran Updated 06 Dec 2026
12 min read ·Lesson 72 of 205

The previous lesson asked whether a path exists. A script often needs to know more: is this a regular file or a directory, can the current user read it, can the script write to it, can it be run as a program? Bash answers these questions with a second group of file test operators. Using them before acting lets a script print a clear message, choose a different action, or stop early, instead of failing halfway through with an error from some other command.

Understanding the Concept

Every file on a Linux system has a type and a set of permissions.

  • The type says what kind of object the path is: a regular file, a directory, a symbolic link, a device, a named pipe, or a socket.
  • The permissions say who may read, write, or execute it. Three groups of people are distinguished: the owner, the group, and everyone else. Each group can be given read (r), write (w) and execute (x) rights.

You can see both with ls -l or stat:

stat -c '%A %U %n' file.txt run.sh dir link.txt

Output:

-rw-r--r-- nobody file.txt
-rwxr-xr-x nobody run.sh
drwxr-xr-x nobody dir
lrwxrwxrwx nobody link.txt

The first character of the mode string is the type: - for a regular file, d for a directory, l for a symbolic link. The next nine characters are the three groups of rwx rights. File test operators let a script ask the same questions that you answer by reading this listing, and they do it for the user who is running the script.

The -c '%A %U %n' option is specific to GNU stat. On macOS, stat uses different options, so treat this command as an inspection tool for Linux rather than something a portable script depends on.

How It Works

A permission test does not read the mode string and apply the rules itself. It asks the operating system whether the current process would be allowed to perform the operation. That makes the answer depend on who is running the script. A file with mode 600 owned by another user is unreadable for you and readable for its owner, so [ -r file ] can give different answers when two people run the same script.

All the operators follow the pattern from lesson 68: a unary operator followed by a path, placed inside [ ] or [[ ]], producing exit status 0 for true and a non-zero status for false. When the path does not exist, every one of these tests is false.

Testing File Types

These operators check the kind of object at a path:

OperatorTrue when the path is
-f patha regular file
-d patha directory
-L path or -h patha symbolic link (the link itself, even if it is broken)
-p patha named pipe (FIFO)
-S patha socket
-b patha block device, such as a disk
-c patha character device, such as a terminal or /dev/null

Here they are applied to a few objects created for the example:

mkdir dir
printf 'data\n' > file.txt
ln -s file.txt link.txt
mkfifo pipe1

[ -f file.txt ];  echo "-f file: $?"
[ -d dir ];       echo "-d dir: $?"
[ -L link.txt ];  echo "-L link: $?"
[ -p pipe1 ];     echo "-p pipe1: $?"
[ -c /dev/null ]; echo "-c /dev/null: $?"
[ -b /dev/null ]; echo "-b /dev/null: $?"

Output:

-f file: 0
-d dir: 0
-L link: 0
-p pipe1: 0
-c /dev/null: 0
-b /dev/null: 1

Every test matches one kind of object, and the device /dev/null is a character device, so -c is true and -b is false. Block devices, character devices and sockets are rare in everyday scripts. The two you will use constantly are -f and -d.

Note that -f and -d follow symbolic links. A link that points to a regular file passes -f, as lesson 71 showed. Only -L and -h look at the link itself.

Testing Permissions

Three operators check the rights of the user running the script:

OperatorTrue when the current user can
-r pathread the path
-w pathwrite to the path
-x pathexecute the path (for a directory: enter it)

The meaning of x on a directory is easy to miss. To cd into a directory, or to open a file inside it by name, you need x on the directory. Having only r lets you list the names but not use them.

Here is a set of files with different modes, tested by an ordinary user (not the administrator):

chmod 644 file.txt      # rw-r--r--
chmod 755 run.sh        # rwxr-xr-x
chmod 000 locked.txt    # ----------
chmod 444 readonly.txt  # r--r--r--

[ -r file.txt ];     echo "-r file.txt: $?"
[ -w file.txt ];     echo "-w file.txt: $?"
[ -x file.txt ];     echo "-x file.txt: $?"
[ -x run.sh ];       echo "-x run.sh: $?"
[ -r locked.txt ];   echo "-r locked.txt: $?"
[ -w readonly.txt ]; echo "-w readonly.txt: $?"
[ -r readonly.txt ]; echo "-r readonly.txt: $?"

Output:

-r file.txt: 0
-w file.txt: 0
-x file.txt: 1
-x run.sh: 0
-r locked.txt: 1
-w readonly.txt: 1
-r readonly.txt: 0

Reading the results against the modes explains each line. The owner of file.txt has rw-, so reading and writing pass and executing fails. run.sh has x set, so -x passes. locked.txt has no rights at all, so even its owner cannot read it. readonly.txt can be read but not written.

Permission Tests Follow the User

The administrator account, root, is treated differently. Running the same checks as root gave:

root -r locked (000): 0
root -w readonly (444): 0
root -x noexec (644): 1
root -x locked (000): 1

The administrator can read and write files regardless of their mode, so -r and -w are true even for mode 000. Executing is different: -x on a regular file is true only when at least one execute bit is set, even for root. A script that tests permissions while running as root, for example inside a container, therefore cannot use -r and -w to discover whether a file's mode is restrictive. Lesson 68 made the same point about the administrator account and these two operators.

Checking Directories

For a directory, the three operators answer three separate questions:

[ -w dir ]; echo "can create files in dir: $?"
[ -x dir ]; echo "can enter dir: $?"

Output:

can create files in dir: 0
can enter dir: 0

To place a new file in a directory, a user needs both w and x on that directory. A script that must write a log file there should test both:

logdir=/var/log/myapp

if [ -d "$logdir" ] && [ -w "$logdir" ] && [ -x "$logdir" ]; then
    echo "log directory is usable"
else
    echo "cannot write to $logdir" >&2
fi

The directory named closed in the experiment had mode 600 (rw- for the owner and nothing else). It shows how the answers can split:

[ -r closed ]; echo "-r closed: $?"
[ -x closed ]; echo "-x closed: $?"

Output:

-r closed: 0
-x closed: 1

The owner may list the names in the directory but may not enter it or open anything inside.

Checking Who Owns a File

Two operators compare a file with the current user:

OperatorTrue when
-O paththe path is owned by the current effective user
-G paththe path's group matches the current effective group
[ -O file.txt ];       echo "-O file.txt: $?"
[ -O /etc/hostname ];  echo "-O /etc/hostname: $?"

Output:

-O file.txt: 0
-O /etc/hostname: 1

The file created by the user is owned by that user, and the system file is owned by root, so the second test fails for an ordinary user. A script can use -O before a command such as chmod that only the owner may run.

Special Permission Bits

Three operators check the special bits that appear in the mode string as s or t:

OperatorTrue when the path has
-u paththe setuid bit: the program runs with its owner's rights
-g paththe setgid bit
-k paththe sticky bit
[ -u /usr/bin/passwd ]; echo "setuid passwd: $?"
[ -k /tmp ];            echo "sticky /tmp: $?"

Output:

setuid passwd: 0
sticky /tmp: 0

On the test machine, ls -ld showed -rwsr-xr-x for /usr/bin/passwd (the s is the setuid bit) and drwxrwxrwt for /tmp (the final t is the sticky bit, which lets users delete only their own files there). These tests are used mostly in security audits, a topic that returns in lessons 154 to 161.

Checking Whether Input or Output Is a Terminal

The -t operator takes a file descriptor number instead of a path. It is true when that descriptor is connected to a terminal:

[ -t 0 ]; echo "stdin is a terminal: $?"
[ -t 1 ]; echo "stdout is a terminal: $?"

Typed into an interactive terminal, both lines print 0. When the same commands run with their input or output redirected, the result is 1. In the test environment, output was captured, so both printed 1:

stdin is a terminal: 1
stdout is a terminal: 1

This is how a script decides whether to ask questions or print colors. If standard output goes to a file or another command, color codes would only clutter the result, so scripts often print them only when [ -t 1 ] is true. Standard input and output were the subject of lesson 56.

Choosing Between Tests Before Running a File

Before running a script, you can tell the user precisely what is wrong:

for s in run.sh noexec.sh missing.sh; do
    if [ -x "$s" ]; then
        echo "$s: executable"
    elif [ -e "$s" ]; then
        echo "$s: exists but not executable"
    else
        echo "$s: not found"
    fi
done

Output:

run.sh: executable
noexec.sh: exists but not executable
missing.sh: not found

The if ... elif ... else chain works through the questions from most specific to least specific: it first asks whether the file can be run, then whether it exists at all, and finally concludes that it is missing. Without these checks, running ./noexec.sh produces only a terse error and exit status 126:

bash: ./noexec.sh: Permission denied

A related check is whether a command is available, which is a question about the PATH rather than a file. The command -v builtin prints the path of a command and returns status 0 when it exists:

command -v bash
command -v nosuchtool; echo "status: $?"

Output:

/usr/bin/bash
status: 1

The printed path for bash depends on the system. Combining command -v with -x confirms that the program is both found and runnable:

[ -x "$(command -v bash)" ]; echo "bash found and executable: $?"

Output:

bash found and executable: 0

Combining Tests with Bash Conditionals

Several conditions can be joined inside one [[ ]]:

[[ -f file.txt && -r file.txt ]]; echo "readable regular file: $?"
[[ -d dir && -w dir && -x dir ]]; echo "usable directory: $?"

Output:

readable regular file: 0
usable directory: 0

With [ ], write the tests separately and join them with && or ||. The operators -a and -o also exist inside [ ], but they can be ambiguous. Lesson 74 covers logical operators in detail.

One more detail that causes confusion: -a also has an old meaning as a unary file test, equal to -e. Both [ -a file.txt ] and [[ -a file.txt ]] were true for an existing file. Dash rejects the unary form (sh: 1: [: -a: unexpected operator). Use -e in new scripts, because -a has two meanings, is easy to misread, and is not portable.

Practical Applications

A script that processes a log file only after confirming it is a readable regular file, and gives a specific message for each problem:

#!/usr/bin/env bash

log="$1"

if [ ! -e "$log" ]; then
    echo "error: $log does not exist" >&2
    exit 1
elif [ ! -f "$log" ]; then
    echo "error: $log is not a regular file" >&2
    exit 1
elif [ ! -r "$log" ]; then
    echo "error: $log is not readable by $(id -un)" >&2
    exit 1
fi

grep -c ERROR "$log"

Each branch handles one reason the file cannot be used. Printing the user name with $(id -un) makes the permission message easier to understand when the script runs under a different account. The exit 1 lines end the script with a failure status, which lesson 118 explains, and the >&2 redirections send the messages to standard error.

A script that decides at startup whether it may use colors:

if [ -t 1 ]; then
    green=$'\033[32m'
    reset=$'\033[0m'
else
    green=""
    reset=""
fi

echo "${green}done${reset}"

When run in a terminal, the word done appears in green. When the output is piped or redirected, the variables are empty and only the plain word is printed. The $'...' form for escape characters comes from lesson 47.

Portability

Under Dash, the shell behind sh on Debian and Ubuntu, the operators -O, -G, -k, -u and -p all worked inside [ ] in the test, and so did the ones from lesson 71. The one exception is the unary -a, which Dash rejects. The [[ ]] form does not exist in Dash at all (lesson 71). The tests -e, -f, -d, -r, -w, -x, -s and -L are the safest choice for scripts that must run on any system, because they are the ones the POSIX standard describes most widely. Other shells and older systems may support fewer operators than the Dash version tested here. Always quote every variable.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Checking File Types and Permissions and get answers drawn from it.

Signed-in readers only.