【问题标题】:How to tell shell command tail not to wait for parameter如何告诉shell命令tail不要等待参数
【发布时间】:2013-09-04 15:25:21
【问题描述】:

我当前的代码

tail -n 1 `ls -1t /path/*.txt 2>/dev/null | head -n 1` | awk '{print $1}'

如果目录中至少有一个*.txt 文件,则可以正常工作。

但如果没有这样的文件,tail 正在等待输入并且不会结束。

我需要如何修改我的代码以确保即使没有文件也能结束?

【问题讨论】:

    标签: linux shell tail


    【解决方案1】:

    做了一个快速测试,将/dev/null 添加为“假”文件似乎可以解决问题。

    tail -n 1 `ls -1t /path/*.txt 2>/dev/null | head -n 1` /dev/null | awk '{print $1}'
    

    【讨论】:

    • 很棒的提示。要使其工作,需要tail -qn 1 而不是tail -n 1
    【解决方案2】:

    我认为您可以在读取时设置超时,如下所示:-

    tail -f *.txt | read -t 30 line
    

    或者这个:-

    if [ -f /path/*.txt ]; then 
       tail -n 1 `ls -1t /path/*.txt 2>/dev/null | head -n 1` | awk '{print $1}'
    fi 
    

    【讨论】:

    • @KarolyHorvath 在 ksh 中运行良好。请测试。
    【解决方案3】:

    一个简单的 if 语句来检查文件是否存在可能是最好的和最少混淆的方法。 克什:

    if [ -f /path/*.txt ]; then 
        tail -n 1 `ls -1t /path/*.txt 2>/dev/null | head -n 1` | awk '{print $1}'
    fi 
    

    添加不同的bash语法

    files=(f/path/*.txt)
    if [ -f ${files[0]} ];
        tail -n 1 `ls -1t /path/*.txt 2>/dev/null | head -n 1` | awk '{print $1}'
    fi 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-08
      • 2020-07-29
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 2019-11-21
      • 2010-12-17
      相关资源
      最近更新 更多