Sometimes you may need to check if directory exists in shell script. In this article, we will look at how to create shell script to check if directory exists in Linux.
How to Check if Directory Exists in Shell Script
Here are the steps to check if directory exists in shell script in Linux.
1. Create empty shell script
Open terminal and run the following command to create empty shell script file.
$ sudo vi dir_check.sh
2. Add Shell Script
Add the following shell script to test if directory exists or not.
#!/bin/sh
if [ -d "$1" ]
then
echo "Directory $1 exists"
else
echo "Directory $1 does not exist"
fi
Save and close the file. In the above code, we use $1 to capture the directory path specified via command line argument.
3. Make the Shell Script Executable
Change the shell script’s file permission to make it executable.
$ sudo chmod +x dir_check.sh
4. Test the Shell Script
Run the shell script on your choice of directories to see if they exist or not. Here are some examples.
$ ./dir_check.sh /home/ubuntu Directory /home/ubuntu exists $ ./dir_check.sh /abc/xyz Directory /abc/xyz does not exist
That’s it. In this article, we have looked at how to create a simple shell script to check if a directory is present or not.
Also read:
Shell Script to Delete Files in Directory
VirtualHost for Wildcard Subdomain in Apache Server
How to Fix NGINX: Upstream Closed Prematurely Error
How to Block Referrer Spam in Apache .htaccess
How to Pass Parameters in Shell Script
Related posts:
How to Install .deb File in Ubuntu
How to Add Header in CSV File Using Shell Script
How to Debug Shell Script
How to Save Command Output to File in Linux
How to Delete Multiple Directories in Linux
How to Setup Email Alerts for Root Login in Linux
How to Get Hostname/Domain Name from IP Address in Linux
How to Recover Deleted Files in Linux

Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.