Bash script check if directory exists

Use Bash script check if the directory exists or not exists.  In this tutorial, I will check FILE/FOLDER exists or NOT exists and Check Symbolic Link. Bash script the essential for DevOps Roles.

The syntax bash script check if directory exists

if [ -d "/path/to/directory" ] 
then
    echo "Directory /path/to/directory is exists." 
fi

Or syntax Bash script check if directory not exists

if [ ! -d "/path/to/directory" ] 
then
    echo "Directory /path/to/directory is NOT exists." 
    exit 99
fi

Check if the file is exists

if [ -f "/path/to/file" ]
then
    echo "File /path/to/file is exists."
fi

Example Bash script checks if the directory exists or file exists.

#!/bin/bash
_FILE="/home/huupv/devopsroles/folder/file.txt"
_LINK_DIR="/home/huupv/devopsroles/link_folder"

# Check Directory and File is exists
if [ -f "${_FILE}" ]
then
    echo "File ${_FILE} is exists."
    _DIR=$(dirname ${_FILE})

  if [ -d "${_DIR}" ]
  then
      echo "Directory /path/to/directory is exists."
  fi
fi
# Check Symbolic link
ls -la /home/huupv/devopsroles/ | grep "\->"
# Check Symbolic link is exists
if [ -L "${_LINK_DIR}" ]
then
    echo "Directory ${_LINK_DIR} is a symlink."
fi
# Check Directory is NOT exists
if [ ! -d "/home/huupv/devopsroles/folder2" ]
then
    echo "Directory /home/huupv/devopsroles/folder2 is NOT exists."
    exit 99; # ERROR code 99
fi

The screen output terminal:

Bash script check if directory exists

Summary check File/Folder exists or NOT exists

  • -L “FILE“: FILE/FOLDER exists and is a symbolic link
  • -d “Directory“: FILE exists and is a directory
  • -f “FILE” : FILE exists

Conclusion

Through the article, you can use the Bash script check if directory exists as above. I hope will this your helpful. For more details refer to the Bash script.

About HuuPV

My name is Huu. I love technology, especially Devops Skill such as Docker, vagrant, git, and so forth. I like open-sources, so I created DevopsRoles.com to share the knowledge I have acquired. My Job: IT system administrator. Hobbies: summoners war game, gossip.
View all posts by HuuPV →

Leave a Reply

Your email address will not be published. Required fields are marked *

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