0

I have tried with this one day but still i cant figure out why? echo is working fine but if is always return false.

#!/bin/sh -e
   scan_fileExists(){
        while read file; do
            echo $file #echo is working
            if [ -f $file ]; then
                echo "Yes"
            fi
        done < $1
   }
   scan_fileExists "/home/myfile"
5
  • /home/myfile is simple file with 3 text lines Commented Mar 24, 2015 at 5:23
  • I guess your problem is that "Yes" is not getting printed at all? What are the 3 text lines in /home/myfile? are they filenames? Commented Mar 24, 2015 at 5:26
  • if [ -f "$file" ]; then ... (Note the quotes..) Also, are you sure these files exist? Commented Mar 24, 2015 at 5:33
  • Yes AMD you're correct, its not getting printed at all rather than i hard code the file path instead of use $file; yes /home/myfile inclusing file names Commented Mar 24, 2015 at 5:34
  • I have tried both with and without quotes,yes files are exists; Commented Mar 24, 2015 at 5:36

1 Answer 1

1

Try this:

#!/bin/bash -e                               # modified
   scan_fileExists(){
        x=$'\r'                              # added
        while read file; do
            echo $file #echo is working
            if [ -f ${file%${x}*} ]; then    # modified
                echo "Yes"
            fi
        done < $1
   }
   scan_fileExists "/home/myfile"

Other method to keep sh as shell (disadvantage: while runs as member of a pipe in a subshell):

#!/bin/sh -e
   scan_fileExists(){
        tr -d "\r" < $1 | while read file; do  # modified
            echo $file #echo is working
            if [ -f $file ]; then
                echo "Yes"
            fi
        done                                   # modified
   }
   scan_fileExists "/home/myfile"
Sign up to request clarification or add additional context in comments.

2 Comments

Yes its working perfectly, could you please describe whats the wrong with my snippet and what is the logic behind your script any way superb and thank you very much
Your /home/myfile contains at end of each line an additional disturbing carriage return (hex 0d). Unix/Linux uses only a newline (hex 0a) to mark end of line, Windows uses newline and carriage return.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.