bash继续执行命令失败

时间:2014-06-13 09:39:24

标签: bash

#! /bin/bash

while :
do
    filenames=$(ls -rt *.log | tail -n 2)
    echo $filenames
    cat $filenames > jive_log.txt
    sleep 0.1
done

我正在尝试从目录中读取最新的2个文件,并使用bash加入它们。 但是,如果当前目录中没有带扩展名.log的文件,则ls -rt *.log命令将失败并显示error "ls: cannot access *.log: No such file or directory"。错误之后,看起来while循环不会执行。 之后我是这样做的,即使一个命令失败,无限循环也会继续。

2 个答案:

答案 0 :(得分:1)

我不确定你的意思,但也许:

for (( ;; )); do
    while IFS= read -r FILE; do
        cat "$FILE"
    done < <(exec ls -rt1 *.log  | tail -n 2) >> jive_log.txt
    sleep 1
done

请注意ls选项-1逐行打印文件。

无论如何,您可以将最后两个文件加入jive_log.txt:

while IFS= read -r FILE; do
    cat "$FILE"
done < <(exec ls -rt1 *.log  | tail -n 2) >> jive_log.txt

另一种方法是将其保存到数组(例如使用readarray),然后将最后2个元素传递给cat。

readarray -t FILES < <(exec ls -rt1 *.log)
cat "${FILES[@]:(-2)}" > jive_log.txt  ## Or perhaps you mean to append it? (>>)

答案 1 :(得分:1)

如果要对find的输出进行排序,则必须在开头添加排序键,稍后可以将其删除。

find . -name \*.log -printf '%T+\t%p\n' |
sort -r |
head -2 |
cut -f 2-

使用head代替tail会稍微便宜一些。

相关问题