#! /bin/bash

echo -e "Enter the name of the file : \c"
read file_name

if [ -e $filename ]
echo "$file_name is found"
echo "$file_name is not found"

i'm running the above to check the file exists in the current directory using flag -e, but it is showing the condition as $filename is found for any value given for $filename.

  • 6
    You either have a typo in your script or a copy/paste error here. read file_name --> if [ -e $filename ]. You also should double-quote your variable if [ -e "${file_name}" ]. shellcheck.net is a nice tool to fine problems with shell scripts. – Thomas May 11 at 8:14
  • 2
    You are reading filename in file_name variable but comparing filename. Value of filename will be empty by default. Be cautious with variable names. – Kulfy May 11 at 8:46
  • 2
    Add a set -x at the beginning of the script just after the #! line to properly debug your script! – George Udosen May 11 at 9:12
  • 1
    No, your doing it wrong. Put the set -x on a line of it's own! – George Udosen May 11 at 10:01
  • 1
    @GeorgeUdosen its working now thanks! – azardin May 11 at 10:05

I made a few changes to your script:

  • # !/bin/bash although it works is unconventional. Use #!/bin/bash instead.
  • Filename is one word but often we think it is two. Consequently it was spelled differently as file-name and file_name
  • Cosmetically lines between if -> else -> fi should be indented for greater readability. It still works vertically aligned it's just easier to read when indented.
  • Extra words in Enter the name of the file can be shortened to Enter filename to make programs shorter and faster. This also makes it quicker for people to read instructions.

echo -e "Enter filename: \c"
read filename

if [ -e "$filename" ]
    echo "$filename found"
    echo "$filename not found"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.