Bash readline在while循环中不起作用

时间:2015-03-24 05:19:51

标签: linux bash loops scripting do-while

我有一天试过这个但仍然无法找出原因? echo工作正常,但如果总是返回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"

1 个答案:

答案 0 :(得分:1)

试试这个:

#!/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"

sh保留为shell的其他方法(缺点:在子shell中作为管道成员运行时):

#!/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"