【问题标题】:If else in xargs如果在 xargs 中其他
【发布时间】:2013-09-25 09:18:56
【问题描述】:

我想比较 tail -1 的输出,看它是否为空字符串。例如,如果我正在使用 find 搜索文件,并且想将结果与“”(空字符串)进行比较,我该怎么做?我有:

find . -name "*.pdf" | tail -1 | xargs -L1 bash -c 'if [$1 == ""] then echo "Empty"; else 
< echo $1; fi'

基本上,如果文件名不为空,它会打印出文件名,如果'find'没有找到pdf文件,它会打印“Empty”。

我尝试了许多不同的变体,在单个命令中使用 if-else 语句,但似乎没有任何效果。

【问题讨论】:

    标签: linux bash shell command-line-arguments


    【解决方案1】:

    你可以写一个脚本:

    #!/bin/bash
    output=$(find . -name *.pdf)
    if [ -z $output ]; then
        echo "Empty"
    fi
    

    【讨论】:

    • 如何在 xargs 的上下文中输入它?是在 bash -c 里面吗?
    【解决方案2】:

    您不需要将输出通过管道传送到tailxargs 等等...

    简单地说:

    (( $(find . -name "*.pdf" | wc -l) == 0)) && echo "Empty"
    

    【讨论】:

    • @user680936 它计算输出中的行数。
    • 还有一个问题,else 语句在哪里?如,如果它不为空,我只是打印出文件名
    • 使用||。例如,说:(( $(find . -name "*.pdf" | wc -l) == 0)) &amp;&amp; echo "Empty" || $(find . -name "*.pdf" | tail -1)
    【解决方案3】:

    试试这个:

    find . -name "*.pdf" | xargs -L1 bash -c 'if [ -s $0 ] ; then echo "$0"; else echo "File empty"; fi'
    

    根据man test -s 会检查文件大小是否为零。

    【讨论】:

    • 出于某种原因,这并没有为我输出任何东西。我认为这可能是因为它没有在 if 子句中进行比较。 -s 指的是什么? $0 是否与文件名匹配?
    • 啊,对不起,-s 检查文件大小...你已经提到了。
    • 刚刚意识到我以为您想为每个内容为空的 pdf 文件打印“空”,如果没有 pdf 文件,则不打印空。
    【解决方案4】:

    您可以改用函数。

    function tailx {
        if read -r LINE; then
            (
                echo "$LINE"
                while read -r LINE; do
                    echo "$LINE"
                done
            ) | command tail "$@"
        else
            echo "Empty."
        fi
    }
    

    您可以将其放在~/.profile~/.bashrc 中。运行 exec bash -l 以重新加载您的 bash 并运行 find . -name "*.pdf" | tailx -1。您还可以将其自定义为将/usr/local/bin 放置为/usr/local/bin/tailx 的shell 脚本。只需在脚本末尾添加tailx "$@",并在开头添加shell头即可。

    #!/bin/bash
    ...
    tailx "$@"
    

    【讨论】:

      【解决方案5】:

      对于xargs,您可以使用选项--no-run-if-empty

      --no-run-if-empty

      -r

      如果标准输入不包含任何非空格,请不要运行该命令。通常,即使没有,该命令也会运行一次 输入。此选项是 GNU 扩展。

      我的用例示例:

      find /iDontExist | xargs du -sc
      # produce the command `du -sc` on the current directory
      # that wasn't the initial aim
      

      避免这种情况的方法:

      find /iDontExist | xargs --no-run-if-empty du -sc
      

      【讨论】:

      • 不确定这是否真的解决了 OPs 问题,但它确实非常简单地解决了我的问题。谢谢
      猜你喜欢
      • 2020-06-20
      • 2016-07-05
      • 1970-01-01
      • 1970-01-01
      • 2015-08-17
      • 1970-01-01
      • 2012-07-18
      • 2023-03-30
      • 1970-01-01
      相关资源
      最近更新 更多