Bash: Check If File or Directory Exists

Learn how to use Bash commands to verify the presence of files and directories on your Linux system.

Apr. 10, 2026 at 6:13am

An extreme close-up of a sleek, matte black command-line interface device with clean, geometric lines and subtle metallic accents, conceptually representing the precision and reliability of Bash scripting for file and directory management.A minimalist, high-tech device showcases the power of Bash scripting to reliably check for file and directory existence.Brice Today

This guide explains how to use Bash scripting to determine whether a file or directory exists on a Linux system. It covers the test command, square brackets, and code snippets to check for the existence of specific files and directories, as well as how to handle cases where a file or directory does not exist.

Why it matters

Knowing how to check for the existence of files and directories is a fundamental skill in Bash scripting. This capability allows scripts to make informed decisions, handle errors gracefully, and automate tasks that depend on the presence of necessary resources.

The details

The test command and square brackets can be used to check if a file or directory exists. The -f option checks for a file, while the -d option checks for a directory. If the file or directory exists, the command returns 0 (true), otherwise it returns 1 (false). Code snippets can also be used to check for multiple files or directories at once using conditional statements.

  • The guide was published on 2026-04-10.

The players

Linux

The operating system used in the examples and instructions.

Got photos? Submit your photos here. ›

The takeaway

This guide provides a comprehensive overview of how to use Bash scripting to check for the existence of files and directories on a Linux system. By understanding these techniques, users can write more robust and reliable scripts that can handle various scenarios and ensure the necessary resources are available before proceeding with operations.