无法读取带有路径的文件并检查它们是否存在

时间:2016-08-31 15:35:18

标签: shell unix

我正在尝试检查某些路径是否存在。路径位于文本文件

这是文本文件:

<volume>

路径/cygdrive/c/scriptstest/test1 /cygdrive/c/scriptstest/test2 /cygdrive/c/scriptstest/test3 /cygdrive/c/scriptstest/test4 test1test2存在。

我的代码是

test3

问题在于:

while read -r line;
do
    echo $line
    if [ -d $line ];  then
        echo "Exist"
    else
        echo  "No exist"
    fi
done < test2.txt

结果总是否定的,但是当我将路径直接复制并粘贴到代码中时,结果就可以了:

/cygdrive/c/scriptstest/test1
No exist

/cygdrive/c/scriptstest/test2
No exist

/cygdrive/c/scriptstest/test3
No exist

/cygdrive/c/scriptstest/test4
No exist

为什么这不适用于脚本?

1 个答案:

答案 0 :(得分:1)

The problem was the paths.txt file. It had been saved with DOS line endings - so I was actually testing for a directory name ending with a carriage return. That wasn't obvious when printing (and would have been more obvious with printf '%q\n' "$line" instead of echo $line).

Removing the carriage returns from the line ends fixed the problem.