管道运行时增加bash变量 [英] increment bash variable when piping to function

查看:63
本文介绍了管道运行时增加bash变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to do the following:

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'.
我已经见过此线程,但不适用于我的情况-尝试时会出现语法错误.

But the increment doesn't work, the variable c stays '1'.
I've seen this thread, but it doesn't work for my case - when I try it, a syntax error appears.

推荐答案

此打印:

test#1
test again#2

您是否使用#!/bin/bash 作为您的爆炸?如果使用#!/bin/sh ,则某些bash扩展名(例如<())将不可用.

Are you using #!/bin/bash as your shebang? If you use #!/bin/sh, some bash extensions (such as <( )) won't be available.

这篇关于管道运行时增加bash变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆