Checking Files with Bash 101

Back in the day, I’d have preferred writing any of this in Perl, no question. For most of my career, if I needed to scan files, parse something, or automate a system, I reached for Perl first. It was fast, powerful, and I knew it inside and out.

But these days, working the way I do now, rebuilding VMs, wiring up new services, testing parts of the CodexMCP stack, I need to wield Bash as well as I used to wield Perl. Because when you’re driving Linux at root level, you need to speak the native tongue.

GPT is helping me with many of these small tools and helpers. I’m not shy about that. But the point is, you need to understand what it’s writing, what each command does, until you can write it blindfolded. That’s why I’m sharing these sessions, because learning Bash (again) is part of the work.

Here’s a quick one: checking files in Bash, the operators you actually need to know. Not a man page dump, just what works when you’re building and testing systems like this.

File Tests

# -s  File exists and is not empty
if [[ -s "$file" ]]; then
    echo "$file is not empty"
fi

# -f  File exists and is a regular file
if [[ -f "$file" ]]; then
    echo "$file is a file"
fi

# -d  File exists and is a directory
if [[ -d "$dir" ]]; then
    echo "$dir is a directory"
fi

# -r  File is readable
if [[ -r "$file" ]]; then
    echo "$file is readable"
fi

# -w  File is writable
if [[ -w "$file" ]]; then
    echo "$file is writable"
fi

# -x  File is executable
if [[ -x "$script" ]]; then
    echo "$script is executable"
fi

# -e  File exists (any type)
if [[ -e "$file" ]]; then
    echo "$file exists"
fi

# -L  File is a symlink
if [[ -L "$link" ]]; then
    echo "$link is a symlink"
fi

String Tests

# -z  String is empty
if [[ -z "$var" ]]; then
    echo "Variable is empty"
fi

# -n  String is not empty
if [[ -n "$var" ]]; then
    echo "Variable is not empty"
fi

Numeric Tests

# -eq  Equal
if [[ $count -eq 5 ]]; then
    echo "Count is 5"
fi

# -ne  Not equal
if [[ $count -ne 5 ]]; then
    echo "Count is NOT 5"
fi

# -lt  Less than
if [[ $count -lt 10 ]]; then
    echo "Count is less than 10"
fi

# -le  Less than or equal
if [[ $count -le 10 ]]; then
    echo "Count is 10 or less"
fi

# -gt  Greater than
if [[ $count -gt 10 ]]; then
    echo "Count is greater than 10"
fi

# -ge  Greater than or equal
if [[ $count -ge 10 ]]; then
    echo "Count is 10 or more"
fi

Combining Tests

# File exists AND is readable
if [[ -f "$file" && -r "$file" ]]; then
    echo "$file exists and is readable"
fi

# Directory exists OR file exists
if [[ -d "$dir" || -f "$file" ]]; then
    echo "Either $dir or $file exists"
fi

This is way more than I actually used in my sshto.sh Bash script. But since I may need this someday, now I have a basic overview of the main operators available and can come back to this page if needed. Hopefully, it will be useful to you also.

--Forever Learning
-Bryan