2012-05-15 31 views
0

我有一个文件包含两个目录路径(将包含更多)。我想阅读每一行,然后在每行上做ls。很简单的权利?For循环,需要输入文件不工作

事情是不工作,我不知道为什么。无论我做什么,最后一行总是很好,ls。之前的行是“不”存在于ls,即使它们存在。

的File.List

/path/to/directory1/ 
/path/to/directory2/ 
/path/to/directory1/ 
/path/to/directory2/ 

当我运行下面的代码片段

DIRECTORIES="file.list" 
for DIR2 in `cat $DIRECTORIES` 
do 
     echo $DIR2 
     ls $DIR2 
done 

我得到的输出

/path/to/directory1/ 
does not exist. file /path/to/directory1/ 
/path/to/directory2/ 
does not exist. file /path/to/directory2/ 
/path/to/directory1/ 
does not exist. file /path/to/directory1/ 
/path/to/directory2/ 
Server 

下面有什么不对呢?其他更好的解决方案?

感谢

编辑:奇怪,我只是试图在另一个Unix机器和工作得很好

回答

2

可能$ DIR2包含行尾?尝试删除它们:

DIR2=`echo $DIR2 | tr -d '\r'` 

我认为是因为张贴的日志对我来说看起来很奇怪。 ls命令的个人电脑上输出如下:

ls: cannot access /path/to/directory1/: No such file or directory

但是你的:

does not exist. file /path/to/directory1/ 
+0

行确实有在该行的最后一些奇怪的字符并工作。我试着用你的方法去除'$ DIR2 = \'echo $ DIR2 | tr -d'[\ n \ r]'\''但没有工作 – esausilva

+0

我犯了一个错字,很抱歉。尝试使用更新后的代码行(左侧没有美元符号)。我已经更新了答案。 – alexander

0

JGeZau,

脚本看起来不错,你检查,你引用你的路径在绝对/相对方面是否正确?

我复制你的脚本在bash和我没有任何问题可言:

test.sh:

#!/bin/bash 
DIRECTORIES="paths" 
for DIR2 in `cat $DIRECTORIES` 
do 
    echo $DIR2 
    ls $DIR2 
done 

路径:

/var/logs/ 
/var/tmp/ 

输出:

./test.sh

/var/logs/ 
file1.log file2.log 

/var/tmp/ 
tmp1 tmp2 tmp3 

希望这可能有所帮助。

+0

奇怪,我只是试图在另一个Unix机器,并通过编辑文件上的纯文本编辑器,我能够删除然后只是正常 – esausilva

1

cat是一个邪恶的计划,最好是不要使用它。您必须逐行读取文件,cat输出不是行缓冲。

while read path ; do 
    ls $path 
done <file.list 
+1

'猫'不是邪恶的,尽管它(经常)被滥用。 –

+0

好吧,猫多半是没用的。 –

+0

猫不是无用的,但它通常在不需要时使用。 –