increment bash variable when piping to function
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开发者_JAVA技巧 -n "test"
} | func
{
echo -n "test"
} | func
But the increment doesn't work, the variable c
stays '1'.
The trick in the linked question works for me:
#!/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")
this prints:
test#1
test again#2
Are you using #!/bin/bash
as your shebang? If you use #!/bin/sh
, some bash extensions (such as <( )
) won't be available.
精彩评论