当管道传递到函数时增加 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"
}
{
echo -n "test"
} | func
{
echo -n "test"
} | func
但是增量不起作用,变量 c
保持为“1”。
我看过此线程,但它不适用于我的情况- 当我尝试时,出现语法错误。
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
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
链接问题中的技巧适用于我:
这会打印:
您正在使用
#!/bin/bash
作为您的 shebang 吗?如果您使用#!/bin/sh
,某些 bash 扩展(例如<( )
)将不可用。The trick in the linked question works for me:
this prints:
Are you using
#!/bin/bash
as your shebang? If you use#!/bin/sh
, some bash extensions (such as<( )
) won't be available.