Bash Script to Check if File is Directory – Example

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 – Simple script to 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.

When the above bash shell script is run in Terminal

 

Example 2 – Check if argument passed to function is a 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.

When the above script is run in Terminal

 

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.