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 Setup 2 Factor Authentication for SSH in Linux
How to Grep Log File Within Specific Time Period in Linux
How to Know Which Shell I am Using in Linux
How To Search in VI Editor
How to Delete Write Protected File in Linux
How to Revoke SSH Access & Keys in Linux
How to Rename Downloaded File in Wget
How to Disable SSH Password Authentication for Some Users

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