Conditional Statements in Shell Scripting: Checking the Existence of a file

Shell Scripting @ Freshers.in

Conditional statements are a fundamental aspect of shell scripting. They allow you to control the flow of your scripts based on specific conditions. In this article, we will explore how to write a shell script that checks if the file ‘data.txt’ exists in the current directory. Depending on the result, the script will print either “File exists” or “File does not exist.”

Use your preferred text editor to create a new file. You can name it something like ‘check_file.sh.’ To create it using the nano text editor, run:

nano check_file.sh

Write the Script

Inside ‘check_file.sh,’ write the following shell script:

#!/bin/bash
# Define the file to be checked
file="data.txt"
# Check if the file exists
if [ -e "$file" ]; then
  echo "File exists"
else
  echo "File does not exist"
fi

This script sets the file variable to ‘data.txt’ and uses the -e flag within a conditional statement to check if the file exists. If the file is found, it prints “File exists”; otherwise, it prints “File does not exist.”

Save the file and exit the text editor (e.g., in nano, press Ctrl + O to save and Ctrl + X to exit).

Before running the script, make it executable using the following command:

chmod +x check_file.sh

Now that the script is executable, you can run it to check the existence of ‘data.txt’ in the current directory:

./check_file.sh

Read more on Shell and Linux related articles

Other urls to refer

  1. PySpark Blogs
Author: user