How to Check if a File or Directory Exists in Bash Scripts

In Bash, use [[ -f "$path" ]] to check that a regular file exists, [[ -d "$path" ]] for a directory, and [[ -e "$path" ]] for anything at that path. Add ! to test that it does not exist. Always quote variables, use [ ] instead of [[ ]] for portable POSIX sh scripts, and remember that a check can become out of date before you act on it, so handle errors from the actual operation too.

Jul 19, 2025 - 11:54
Updated: 
102.1k

Linux Administration in IT Infrastructure · Comparison

How to Check if a File or Directory Exists in Bash Scripts

Quick answer: In Bash, use [[ -f "$path" ]] to check that a regular file exists, [[ -d "$path" ]] for a directory, and [[ -e "$path" ]] for anything at that path. Add ! to test that it does not exist. Always quote variables, use [ ] instead of [[ ]] for portable POSIX sh scripts, and remember that a check can become out of date before you act on it, so handle errors from the actual operation too.

Key takeaways

  • -f regular file, -d directory, -e anything, -L symbolic link.
  • Quote paths: "$file", to handle spaces.
  • [[ ]] is Bash-specific; [ ] works in all POSIX shells.
  • Check permissions with -r, -w, -x; non-empty with -s.
  • Run ShellCheck to catch common mistakes.

Table of Contents

Which Test Operators Are Available?

OperatorTrue if the path
-eexists (any type)
-fis a regular file
-dis a directory
-L or -his a symbolic link
-sexists and is not empty
-r, -w, -xis readable, writable, executable by you
-p, -S, -b, -cis a named pipe, socket, block or character device

Full list in the Bash manual.

What Do Common Checks Look Like?

#!/usr/bin/env bash
config="/etc/myapp/config.yml"
logdir="/var/log/myapp"

if [[ -f "$config" ]]; then
  echo "Config found"
else
  echo "Config missing: $config" >&2
  exit 1
fi

# Create a directory only if it does not exist
[[ -d "$logdir" ]] || mkdir -p "$logdir"

# Not exists
if [[ ! -e "/tmp/lockfile" ]]; then echo "No lock"; fi

# Exists and is not empty
[[ -s "$config" ]] && echo "Config has content"

Note that mkdir -p already succeeds if the directory exists, so the check is optional there.

Should You Use [ ] or [[ ]]?

[ ] / test[[ ]]
PortabilityPOSIX, works in sh, dash, ashBash, Zsh, Ksh only
Word splittingUnquoted variables can breakSafer, but still quote
Extra featuresNonePattern matching, && and || inside

Use [ ] in scripts that start with #!/bin/sh, as defined by the POSIX test utility.

How Do You Check Several Files or a Pattern?

# All required files present?
for f in /etc/myapp/config.yml /etc/myapp/key.pem; do
  [[ -f "$f" ]] || { echo "Missing $f" >&2; exit 1; }
done

# Does any .log file exist? (globs do not work directly with -f when several match)
shopt -s nullglob
logs=(/var/log/myapp/*.log)
if (( ${#logs[@]} )); then echo "${#logs[@]} log files"; fi

How Do You Write a Reusable Check?

require_file() {
  local path="$1"
  if [[ ! -f "$path" ]]; then
    printf 'Error: required file not found: %s
' "$path" >&2
    return 1
  fi
  if [[ ! -r "$path" ]]; then
    printf 'Error: cannot read: %s
' "$path" >&2
    return 1
  fi
}

require_file "/etc/myapp/config.yml" || exit 1

What Mistakes Should You Avoid?

  • Unquoted variables: [ -f $file ] fails with spaces or empty values.
  • Using -f on a directory, or -d on a file.
  • Check-then-act races: another process may delete or create the file between the check and the action (CWE-367). For security-sensitive files, open them directly and handle errors, and create temporary files with mktemp.
  • Following symbolic links unintentionally; test -L first where it matters.

Run ShellCheck on scripts to find these issues automatically: shellcheck myscript.sh. Related: Linux admin commands. WebAsha offers Linux scripting courses.

References

Frequently Asked Questions

Use if [[ -f "$file" ]]; then ... fi for a regular file.

Use [[ -d "$dir" ]], which is true only when the path exists and is a directory.

Negate the test with an exclamation mark: [[ ! -e "$path" ]] is true when nothing exists at that path.

-e is true for any type of path; -f only for regular files.

Use [[ ]] in Bash scripts and [ ] in portable POSIX sh scripts.

Unquoted variables break with spaces or empty values, causing errors or wrong results.

Use [[ -s "$file" ]], which is true only if the file exists and is not empty.

A free tool that analyses shell scripts and warns about common bugs and unsafe patterns.

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Wow Wow 0
Sad Sad 0
Angry Angry 0
Vaishnavi

Vaishnavi is a skilled tech professional at the Ethical Hacking Training Institute in Pune, responsible for managing and optimizing the technical infrastructure that supports advanced cybersecurity education. With deep expertise in network security, backend operations, and system performance, she ensures that practical labs, online modules, and assessments run smoothly and securely. Her behind-the-scenes contributions play a vital role in delivering a seamless and secure learning experience for aspiring ethical hackers.