Bash Script to Check if File is Directory

Bash Script to Check if File is Directory – To check if the specified file is a directory in bash scripting, we shall use  [ -d FILE ]  expression with bash if statement.

  • Example 1 – Simple script to check if file exists and is a directory
  • Example 2 – Check if argument passed to function is a directory

Example 1 – Check if File Exists And is a Directory

We shall consider /home/tutorialkart/ and /home/tutorialkart/sample.txt which are directory and file respectively. We shall verify the same with the help of following bash script.

Bash Script File

#!/bin/bash

# Scenario - File exists and is a directory
if [ -d /home/tutorialkart/ ];
then
	echo "/home/tutorialkart is directory"
else
	echo "/home/tutorialkart is not a directory"
fi

# Scenario - File exists and is not a directory
if [ -d /home/tutorialkart/sample.txt ];
then
	echo "/home/tutorialkart/sample.txt is a directory"
else
	echo "/home/tutorialkart/sample.txt is not a directory"
fi

When the above bash shell script is run in Terminal, we will get the following output.

Output

$ ./bash-script-if-file-is-directory 
/home/tutorialkart is directory
/home/tutorialkart/sample.txt is not a directory

Example 2 – Check if Path is Directory

We shall consider the same file and directory mentioned in the previous example. In this example, we shall write a function whose first argument is a FILE. And in the function we shall check if the passed argument (FILE) exists and is a directory.

Bash Script File

#!/bin/bash

# function to check if passed argument is a directory and exists
checkIfDirectory() {
	# $1 meaning first argument
	if [ -d "$1" ];
	then
		echo "$1 exists and is a directory."
	else
		echo "$1 is not a directory."
	fi
}

# Scenario - File exists and is a directory
checkIfDirectory "/home/tutorialkart/"

# Scenario - File exists and is not a directory
checkIfDirectory "/home/tutorialkart/sample.txt"

When the above script is run in Terminal, we will get the following output.

Output

$ ./bash-script-if-file-is-directory-2 
/home/tutorialkart/ exists and is a directory.
/home/tutorialkart/sample.txt is not a directory.

Conclusion

In this Bash Tutorial – Bash Script to Check if File is Directory, we have come across an example to check if the specified file exists and is a directory.