Introduction to Linux - A Hands on Guide | Linux Bible | Linux From Scratch | A Newbie's Getting Started Guide to Linux | Linux Command Line Cheat Sheet | More Linux eBooks



Monday, 11 November 2013

A Simple BASH Script to Verify Whether A File Exists Under the Specified Path



Time to create an another small and simple BASH script. This time we will check if a file exists under the directory path mentioned by the user. This script will include following steps:

  1. Ask the user to enter the file name.
  2. Ask the user to enter the path to the file.
  3. Check for the READ permission on the specified path.
  4. If READ permission is enabled, check whether the mentioned file exists.
  5. If it exists, tell the user by printing a message on the console.

Script:

#!/bin/bash

# Step 1
echo -n Please Enter the File Name under the test: 
read filename

# Step 2
echo -n “Now, Enter the path to the file : ”
read filepath

#Step 3
if [ -r $filepath ]
then

    #Step 4
    if [ -f ${filepath}/${filename} ]
    then
        
        #Step 5
        echo Yes!! File ${filepath}/${filename} is Found!!

    else
        echo Sorry, File ${filepath}/${filename} is not found.

    fi

# If READ Permission is disabled for the directory
else
echo Access Denied to the Directory $filepath
fi 

0 comments:

Post a Comment