Linux

Check if a directory exists in Linux or Unix shell

[ad_1]

I need to check if a directory exists or not, within a shell script running on Linux or Unix-like system? How do I check if a directory exists in a shell script?

A directory is nothing but a location for storing files on the Linux system in a hierarchical format. For example, $HOME/Downloads/ would store all downloaded files or /tmp/ would store temporary files. This page shows how to see if a directory exists in Linux or Unix-like systems.

 

How to check if a directory exists in Linux

  1. One can check if a directory exists in a Linux shell script using the following syntax:
    [ -d "/path/dir/" ] && echo "Directory /path/dir/ exists."
  2. You can use ! to check if a directory does not exists on Unix:
    [ ! -d "/dir1/" ] && echo "Directory /dir1/ DOES NOT exists."

One can check if a directory exists in Linux script as follows:

OR

Linux check if a directory exists and take some action

Here is a sample shell script to see if a folder exists or not in Linux:

Run it as follows:
./test.sh
./test.sh /tmp/
./test.sh /nixCraft

Bash check if a directory exists in Linux or Unix shell

Check if directory exists in bash and if not create it

Here is a sample shell script to check if a directory doesn’t exist and create it as per our needs:

Make sure you always wrap shell variables such as $DIR in double quotes ("$DIR" to avoid any surprises in your shell scripts:

Using test command

One can use the test command to check file types and compare values. For example, see if FILE exists and is a directory. The syntax is:
test -d "DIRECTORY" && echo "Found/Exists" || echo "Does not exist"
The test command is same as [ conditional expression. Hence, you can use the following syntax too:
[ -d "DIR" ] && echo "yes" || echo "noop"

Getting help

Read bash shell man page by typing the following man command or visit online here:
man bash
help [
help [[
man test

Conclusion

This page explained various commands that can be used to check if a directory exists or not, within a shell script running on Linux or Unix-like systems.

 

Facebook Comments

Show More

Related Articles

Leave a Reply

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

Back to top button