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

Shell Scripting @

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 ‘’ To create it using the nano text editor, run:


Write the Script

Inside ‘,’ write the following shell script:

# Define the file to be checked
# Check if the file exists
if [ -e "$file" ]; then
  echo "File exists"
  echo "File does not exist"

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

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


Read more on Shell and Linux related articles

Other urls to refer

  1. PySpark Blogs
Author: user