Here are the simple steps to check if a file exists in a specific directory using Bash script in linux.
1. Create a new file as mentioned below.
vi script_name.sh
2. Copy and paste below simple Bash script that checks if a file exists in a specific directory:
#!/bin/bash # Specify the directory path and the file name to be checked directory="/path/to/your/directory" file_name="yourfile.txt" # Check if the file exists in the specified directory if [ -e "$directory/$file_name" ]; then echo "The file $file_name exists in $directory." else echo "The file $file_name does not exist in $directory." fi
Note : Replace “/path/to/your/directory” with the actual path of the directory you want to check and “yourfile.txt” with the name of the file you want to verify the existence of.
Here’s a breakdown of the script:
#!/bin/bash : This line specifies the Bash interpreter.
directory =”/path/to/your/directory” : Sets the directory path.
file_name=”yourfile.txt” : Sets the name of the file to be checked.
if [ -e “$directory/$file_name” ]; then : Checks if the file exists in the specified directory.
echo “The file $file_name exists in $directory.” : Prints a message indicating that the file exists.
else : Indicates the start of the code block to be executed if the file does not exist.
echo “The file $file_name does not exist in $directory.” : Prints a message indicating that the file does not exist.
3. Save and close the “vi” editor by pressing “Esc” key and type :wq!
4. Make sure to give execute permissions to the script before running it. You can do this by running the following command in the terminal:
chmod +x script_name.sh
Note : Replace “script_name.sh” with the actual name you save the script as.
Click Here!!! to know how to edit files using VIM editor in linux.
How do you feel about this post? Drop your comments below..