Common If Conditions

Existence checks

Exists

# -n: return true when value is not empty.
if [[ -n "${X}" ]]; then
  echo "X env variable not empty"
fi

Does not exist

# -z: returns true when value is empty.
if [[ -z "${X}" ]]; then
  echo "true when value is empty"
fi

Numerical equality checks

Not Equal

# -ne: not equal operator
if [ "${X}" -ne 0 ]; then
  echo "X is not equal to 0"
fi

Readability check

Is readable check [[ -r "${file:?}" ]]

Using [[ -r file ]] is a good way to check if a file exists and is readable in Bash. However, whether it’s the best way depends on your specific requirements.

When to Use [[ -r file ]]

  • When you want to ensure the file both exists and is readable by the current user.
  • In most bash environments, [[ ]] is preferred over [ ] due to better syntax, built-in support for pattern matching, and fewer surprises with quoting.
if [[ -r "$file" ]]; then
    echo "File exists and is readable"
else
    echo "File is missing or not readable"
fi

🔄 Other Common File Check Options

OptionPurpose
[[ -e file ]]Check if the file exists (but doesn’t check readability).
[[ -f file ]]Check if it’s a regular file (not directory, socket, etc.).
[[ -w file ]]Check if it exists and is writable by the user.
[[ -x file ]]Check if it exists and is executable.

💡 Alternative and Why It May Be Better

If you care more about readability success when opening the file rather than just checking permissions, try actually opening the file instead of relying on -r:

if exec 3< "$file"; then
    echo "File is readable"
    exec 3<&-
else
    echo "File is not readable"
fi

Why? Because -r only checks permissions but doesn’t account for cases where the user may have permissions but still fails to read (e.g., filesystem-level issues).

🚨 Common Pitfalls

  • Symbolic links: -r checks permissions on the target, not the link itself.
  • Directories: -r will return true for readable directories too.
  • Setuid/setgid: May not reflect actual access if elevated privileges are involved.

🔍 Recommendation

  • For basic "does it exist and can I read it?" checks, [[ -r ]] is usually sufficient and preferred.
  • If robustness matters (e.g., for production scripts), use file opening (exec) to test actual readability.
  • Always ensure variables are quoted to avoid filename issues ("$file").


Children
  1. Is Readable Check In Bash