Commands.page Logo

Check If Path Is Directory or File in Ubuntu Bash Script

When developing automation tools on Ubuntu, distinguishing between file types prevents runtime errors and ensures data integrity. This article outlines the specific bash test operators used to identify directories and regular files within a shell script. You will learn the correct syntax to validate paths effectively before executing file operations.

Use Test Operators for Validation

Bash provides built-in test operators to evaluate file types. You can use these operators within square brackets [ ] or with the test command. The most common flags for this task are -d and -f.

Example Script Structure

The following example demonstrates how to implement these checks in a conditional statement. This script assigns a path to a variable and verifies its type before proceeding.

#!/bin/bash

PATH_TO_CHECK="/home/user/example"

if [ -d "$PATH_TO_CHECK" ]; then
    echo "The path is a directory."
elif [ -f "$PATH_TO_CHECK" ]; then
    echo "The path is a regular file."
else
    echo "The path does not exist or is not a standard file type."
fi

Understanding Exit Codes

These test commands rely on exit codes to determine truth. If the condition is met, the command returns an exit status of 0, which bash interprets as true. If the condition fails, it returns 1, interpreted as false. Always quote your variables, such as "$PATH_TO_CHECK", to handle paths containing spaces correctly. This practice ensures your script remains robust across different file naming conventions on Ubuntu.