【问题标题】:increment bash variable when piping to function管道到函数时增加 bash 变量
【发布时间】:2011-07-11 19:24:17
【问题描述】:

我正在尝试执行以下操作:

function func() # in practice: logs the output of a code block to a file
{
    if [ -z "$c" ]; then
        c=1
    else
        (( ++c ))
    fi
    tee -a /dev/null
    echo "#$c"
}

{
echo -n "test"
} | func

{
echo -n "test"
} | func

但是增量不起作用,变量c 保持为“1”。
我见过this thread,但它不适用于我的情况——当我尝试它时,会出现语法错误。

【问题讨论】:

    标签: bash pipe increment


    【解决方案1】:

    linked question 中的技巧对我有用:

    #!/bin/bash
    function func() # in practice: logs the output of a code block to a file
    {
        if [ -z "$c" ]; then
            c=1
        else
            (( ++c ))
        fi
        tee -a /dev/null
        echo "#$c"
    }
    
    func < <(echo -n "test")
    func < <(echo -n "test again")
    

    打印出来:

    test#1
    test again#2
    

    您是否使用#!/bin/bash 作为您的shebang?如果您使用#!/bin/sh,某些 bash 扩展(如&lt;( ))将不可用。

    【讨论】:

    • 管道两边进程需要变量赋值怎么办?
    • 简短回答:你不能,尽管还有其他方法。 Bash 不做多线程,因此管道的每一端都必须在单独的进程中运行,并且单独的进程不能设置彼此的 shell 变量。一些解决方法:首先,您可以运行一个函数,并将输出重定向到一个临时文件,而不是使用管道;然后使用从文件重定向的输入运行另一个。其次,让其中一个函数作为子shell运行,并将相关值存储到临时文件中;然后读取它并将其分配给主 shell 中的变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    相关资源
    最近更新 更多