In this guide, we will learn how to use a Bash script to check if a file or directory exists.
Create File
We need to create a file using the below-given command:
To create a file we use the touch command and “.sh” is the bash file extension.
Open the file and write the script, then save the text by pressing “save”.
One way is to find a file by asking for a filename from the user on a terminal.
Use “-f” to check the file.
Write the below script:
echo "Enter filename"
read newfile1
if [ -f "$newfile1" ]
then
echo "File exists"
else
echo "File does not exist"
fi
Go back to the terminal and run the file to print output:
Permission denied message will be displayed in the terminal.
Make it executable using the following command:
Enter the file name, and the output will be printed:
One way is to find a file by telling the file name while writing code.
We have three ways to write a statement:
[ EXPRESSION ]
[[ EXPRESSION ]]
If [ -f “$filename” ]
If test –f “$fiename.”;
If [[ -Expression ]] ;
Output:
Without using if
The test command can also be used without an if statement. Only if the test command’s exit status is valid, the command after the && operator will be executed.
Output:
Check Multiple Files
Instead of complicated nested if/else constructs, use -a (or && with [[) to check if multiple files exist:
if [ -f new_file.txt -a -f newfile.txt ]; then
echo "Both files exist."
fi
Another way is:
if [[ -f new_file.txt && -f newfile.txt ]]; then
echo "Both files exist."
fi
Output:
Without Using IF Statement
Use the following syntax to check file without using IF:
Conclusion:
This article has shown how to use Bash to search and find if whether a file or directory exists.
If else is used to perform different actions based on the value of the expression used to evaluate whether or not a file or directory exists. Create a nested if-else statement and check the file or directory without using the IF statement.
from Linux Hint https://ift.tt/3upqHRr
0 Comments