Bash Scripting - How to check If File Exists
Last Updated :
16 Jan, 2023
In this article, we will write a bash script to check if files exist or not.
Syntax :
- test [expression]
- [ expression ]
- [[ expression ]]
Here, in expression, we write parameter and file name. Let us see some parameters that can be used in the expression: -
- -f: It returns True if the file exists as a common ( regular ) file.
- -d: it returns True if directory exists.
- -e: It returns True if any type of file exists.
- -c: It returns True if the character file exists.
- -r: It returns True if a readable file exists.
- -w: It returns True if a writable file exists.
- -x: It returns True if an executable file exists.
- -p: It returns True if the file exists as a pipe.
- -S: It returns True if the file exists as a socket.
- -s: it returns True if a file exists and the size of the file is not zero.
- -L: It returns True if the file of symbolic link exists.
- -g: It returns True if the file exists and hold set group id flag is set..
- -G: It returns True if the file exists and holds the same group id that is in process.
- -k: It returns True if the file exists and the sticky bit flag is set.
Now, there are some more parameters for comparison between the two files.
- -ef: It returns True if both files exist and indicate the same file.
Example :
FirstFile -ef SecondFile
- -nt: It returns True if FirstFile is newer than Secondfile.
Example :
FirstFile -nt FileOld
- -ot: It returns True if FirstFile is older than SecondFile.
Example:
FirstFile -ot SecondFile
Let us take some examples based on syntax :
- [ expression ]: First, create a file named " FirstFile.sh " and write the following script on it
#!/bin/bash
# using [ expression ] syntax and in place
# of File.txt you can write your file name
if [ -f "File.txt" ];
then
# if file exist the it will be printed
echo "File is exist"
else
# is it is not exist then it will be printed
echo "File is not exist"
fi
Now save and run the file using the following command
$ chmod +x ./FirstFile.sh
$ ./FirstFile.sh
Output :
Output
Note: As the " File.txt " is present in the system. So, it printed " File is exists ".
- test [expression]: Now, modify the above script in " FirstFile.sh " as follows
#!/bin/bash
# using test expression syntax and in place
# of File2.txt you can write your file name
if test -f "File2.txt" ;
then
# if file exist the it will be printed
echo "File is exist"
else
# is it is not exist then it will be printed
echo "File is not exist"
fi
Now, again save and run the file using the following command
$ chmod +x ./FirstFile.sh
$ ./FirstFile.sh
Output :
Output
Note: As the " File2.txt " is not present in the system. So, it printed " File is not exist ".
- [[ expression ]]: Again modify the above script in " FirstFile.sh " as follows
#!/bin/bash
# using [[ expression ]] syntax and in place
# of File3.txt you can write your file name
if test -f "File3.txt" ;
then
# if file exist the it will be printed
echo "File is exist"
else
# is it is not exist then it will be printed
echo "File is not exist"
fi
Now, again save and run the file using the following command
$ chmod +x ./FirstFile.sh
$ ./FirstFile.sh
Output :
Output
Note: As the " File3.txt " is present in the system. So, it printed " File is exist ".
Let us see an example based on parameters:
- Using -d parameter: Create a file named " FirstDir.sh " and write the following script in it
!/bin/bash
if [[ -d "GFG_dir" ]] ; # Here GFG_dir
is directory and in place of GFG_dir you can write your Directory name
then
echo "Directory is exist" # If GFG_dir exist then it will be printed
else
echo "Directory is not exist" # If GFG_dir is not exist then it will be printed
fi
Now Save and run the file using the following command
$ chmod +x ./FirstDir.sh
$ ./FirstDir.sh
Output :
Output
Note: As the " GFG_dir " is present in the system. So, it printed " Directory is exist ".
Similarly, you can use -f , -e , -w , -r , -c ,etc. ( according to their uses ) in place of -d for checking the existence of different types of files.
Let us see an example based on a comparison of two files :
Create a file name " Comparison_File.sh " and write the following script
#!/bin/bash
# New_file.txt and Old_File.txt are names of two files.
if [[ "New_File.txt" -nt "Old_File.txt" ]] ;
then
# This will be printed if Condition is true
echo "New_File.txt is newer than Old_File.txt"
else
# This will be printed if Condition is False
echo "New_File.txt is not newer than Old_File.txt"
fi
Now Save and run the file using the following command
$ chmod +x ./Comparison_File.sh
$ ./Comparison_File.sh
Output :
Output
Note: As both files are present in the system and " New_File.txt " is newer than " Old_File.txt "
Let us see the example " Check if File does not exist" :
Create a file named " Check_Exist.sh " and write the following script in it
#!/bin/bash
# using ! before -f parameter to check if
# file does not exist
if [[ ! -f "GFG.txt" ]] ;
then
# This will printed if condition is True
echo "File is not exist"
else
# This will be printed if condition is False
echo "File is exist"
fi
Now Save and run the file using the following command
$ chmod +x ./Check_Exist.sh
$ ./Check_Exist.sh
Output :
Output
Note: " GFG.txt " is not present in the system. So, it will print "File is not exist"
Let us see an example without using the If-else condition :
Create a file named " Geeks_File.sh " and write the following script in it
#!/bin/bash
# If File exist then first statement will be
# printed and if it is not exist then 2nd
# statement will be printed.
[ -f "GFG_File.txt" ] && echo "File is exist" || echo "File is not exist"
Now Save and run the file using the following command
$ chmod +x ./Geeks_File.sh
$ ./Geeks_File.sh
Output :
Output
Note: As the " GFG_File.txt " is present in the system. So, it printed " File is exist ".
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Linux Commands Cheat Sheet Linux, often associated with being a complex operating system primarily used by developers, may not necessarily fit that description entirely. While it can initially appear challenging for beginners, once you immerse yourself in the Linux world, you may find it difficult to return to your previous W
13 min read
AVL Tree Data Structure An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read