Member-only story

Checking If a File or Folder Exists in Bash

Javascript Jeep🚙💨
2 min readAug 26, 2024

--

Photo by Gabriel Heinzer on Unsplash

In Bash script we can use -f, -d, and -e options to check for file or folder existence.

-f Operator

The -f operator checks if a specified path exists and is a regular file. A regular file is a file that contains data, as opposed to a directory or a special file (like a device file).

Usage:

if [ -f "filename.txt" ]; then
echo "filename.txt exists and is a regular file."
else
echo "filename.txt does not exist or is not a regular file."
fi

Explanation:

  • -f "filename.txt": This checks whether filename.txt exists and is a regular file.
  • If filename.txt exists and is a regular file, the condition evaluates to true, otherwise evaluates to false .

-d Operator

The -d operator checks if a specified path exists and is a directory. This is useful for verifying the presence of directories.

if [ -d "myfolder" ]; then
echo "myfolder exists and is a directory."
else
echo "myfolder does not exist or is not a directory."
fi

Explanation:

  • -d "myfolder": This checks whether myfolder exists and is a directory.
  • If myfolder exists and is a directory, the…

--

--

Javascript Jeep🚙💨
Javascript Jeep🚙💨

No responses yet