0
for file in /home/TEMP/filename.txt
do
if [ "$file" = /home/TEMP/filename.txt ]
then

echo "$file present"
else

echo "file not present"
fi

its always going to if condition and displaying 'file present' please help

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
Sam
  • 1
  • Possible duplicate of [Check if a file exists with wildcard in shell script](https://stackoverflow.com/questions/6363441/check-if-a-file-exists-with-wildcard-in-shell-script) – JP Ventura Nov 10 '17 at 12:54
  • You are doing a string comparision where both strings are identical! Of yourse this always evaluates to true.... – user1934428 Nov 10 '17 at 14:32

3 Answers3

1

make a file to control if file exists, namely ifExists.sh :

if [ -f $1 ];
then
 echo $1 " is already present"
else
 echo $1 " is not present"
fi

and then, call :

$ . ifExists.sh your_file

or directly call inside your script :

   dir = /home/TEMP; export dir
   file = filename.txt; export file

   if [ -f $dir/$file ];
    then
     echo $dir/$file " is already present"
    else
     echo $dir/$file " is not present"
    fi
Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
0

To check if a file exists:

if [[ -e "$file" ]]

Can you explain a bit more about what exactly you are doing and what your expected results are? What are the contents of the /home/TEMP/filename.txt file?

0

Try with the below scripts

files=`ls ./` # put your path here like `ls /me/you/him/`
for file in $files
do
  echo "$file"
  if [ "$file" == "test2.sh" ];then #put the file name you want to compare here in place of test2.sh
    echo "$file present"
            #if you want to break the loop once file found just add statement `break` here
  else
    echo "file not present"
fi
done
Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17