How to check if a directory or a file exists in system or not using Shell Scripting?
Shell scripting is really a powerful and dynamic way to automate your tasks. To test if a directory or file already exists in the system or not we can use shell scripting for the same along with test command. To proceed with the test script lets first check the test manual. To open a manual use the man command as follows:
man test
Right now we will be covering these two highlighted arguments in your script, further, you can use and test all of them. First, create a shell script file like test.sh using any editor of your choice like nano, vim or sublime and give it executable permissions(chmod +x).
In the below example we are checking if /usr/games directory is present or not.
#!/bin/bash if [ -d /usr/games ]; then echo "The Directory Exists" else echo "The Directory is not present" fi |
Let’s see another example where we have deleted a file from the directory and let’s check what happens.
#!/bin/bash if [ -e /usr/games/master .txt ]; then echo "The file Exists" else echo "The file is not present" fi |
Now we used -e argument to check for the file and we got the message that file is not present as we had deleted it. Like this, you can play with the shell script, refer to the test manual and test more awesome stuff with this.
Recommended Posts:
- How to find time taken by a command/program on Linux Shell?
- Create Directory or Folder with C/C++ Program
- dup() and dup2() Linux system call
- Linux File Hierarchy Structure
- Maximum number of Zombie process a system can handle
- mindepth and maxdepth in Linux find() command for limiting search to a specific directory.
- Introduction to Linux Shell and Shell Scripting
- Write a bash script to print a particular line from a file
- Bash program to check if the Number is a Prime or not
- Making your own Linux Shell in C
- A Shell program To Find The GCD | Linux
- Reverse a String | Shell Programming
- Array Basics Shell Scripting | Set 2 (Using Loops)
- Array Basics in Shell Scripting | Set 1
- Bash program to check if the Number is a Palindrome
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.