为什么Cat命令在脚本中不起作用

时间:2018-07-09 16:27:22

标签: linux bash scripting cat

我有以下脚本,它有一个错误。我正在尝试将所有文​​件合并为一个大文件。通过命令行,cat命令可以正常工作,并将内容打印到重定向的文件中。通过脚本,它可以在某个时间运行,而在其他时间则不能。我不知道为什么它的行为异常。请帮忙。

#!/bin/bash

### For loop starts ###

for D in `find . -type d`
do

        combo=`find $D -maxdepth 1 -type f -name "combo.txt"`
        cat $combo >> bigcombo.tsv

done

这是bash -x app.sh

的输出
++ find . -type d
+ for D in '`find . -type d`'
++ find . -maxdepth 1 -type f -name combo.txt
+ combo=
+ cat
^C

更新: 以下对我有用。路径有问题。我仍然不知道问题出在什么地方,所以欢迎回答。

#!/bin/bash

### For loop starts ###
rm -rf bigcombo.tsv

for D in `find . -type d`
do

                psi=`find $D -maxdepth 1 -type f -name "*.psi_filtered"`
                # This will give us only the directory path from find result i.e. removing filename.
                directory=$(dirname "${psi}")
                cat $directory"/selectedcombo.txt" >> bigcombo.tsv


done

1 个答案:

答案 0 :(得分:2)

一个明显的问题是您试图cat一个不存在的文件。

次要问题与效率和正确性有关。最好避免运行两个嵌套循环,尽管将操作分为两个步骤仅是微不足道的。内部循环最多只会执行一次。将命令结果捕获到变量中是常见的初学者反模式;通常可以避免只使用一次的变量,并且避免乱码乱扔外壳的内存(同时解决了缺少引号的多个问题-包含文件或目录名称的变量基本上应该始终用双引号内插)。重定向最好在任何包含循环之外执行;

rm file
while something; do
    another thing >>file
done

将打开,查找到文件末尾,写入和关闭文件,循环次数不计其数,而

while something; do
    another thing
done >file

仅执行一次open,seek和close操作,并且避免在开始循环之前必须清除文件。尽管您的脚本可以重构为根本没有任何循环;

find ./*/ -type f -name "*.psi_filtered" -execdir cat selectedcombo.txt \;> bigcombo.tsv

根据您的问题,目录包含combo.txt但不包含任何*.psi_filtered文件可能是错误的。也许您想locate and examine these directories.

相关问题