Check if a File or Directory Exists in Bash

Check if File Exist

FILE=/etc/resolv.conf
if test -f "$FILE"; then
    echo "$FILE exist"
fi
FILE=/etc/resolv.conf
if [ -f "$FILE" ]; then
    echo "$FILE exist"
fi
FILE=/etc/resolv.conf
if [[ -f "$FILE" ]]; then
    echo "$FILE exist"
fi

Check if Directory Exist

FILE=/etc/docker
if [ -d "$FILE" ]; then
    echo "$FILE is a directory"
fi

Check if File does Not Exist

FILE=/etc/docker
if [ ! -f "$FILE" ]; then
    echo "$FILE does not exist"
fi

Check if Multiple Files Exist

FILE=/etc/docker
if [ -f /etc/resolv.conf -a -f /etc/hosts ]; then
    echo "$FILE is a directory"
fi
FILE=/etc/docker
if [ -f /etc/resolv.conf && -f /etc/hosts ]; then
    echo "$FILE is a directory"
fi

File test operators

  • -f FILE – True if the FILE exists and is a regular file (not a directory or device).
  • -G FILE – True if the FILE exists and has the same group as the user running the command.
  • -h FILE – True if the FILE exists and is a symbolic link.
  • -g FILE – True if the FILE exists and has set-group-id (sgid) flag set.
  • -k FILE – True if the FILE exists and has a sticky bit flag set.
  • -L FILE – True if the FILE exists and is a symbolic link.
  • -O FILE – True if the FILE exists and is owned by the user running the command.
  • -p FILE – True if the FILE exists and is a pipe.
  • -r FILE – True if the FILE exists and is readable.
  • -S FILE – True if the FILE exists and is socket.
  • -s FILE – True if the FILE exists and has nonzero size.
  • -u FILE – True if the exists and set-user-id (suid) flag is set.
  • -w FILE – True if the FILE exists and is writable.
  • -x FILE – True if the FILE exists and is executable.

References
https://linuxize.com/post/bash-check-if-file-exists/

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.