问题
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.
回答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.
来源:https://stackoverflow.com/questions/6655323/increment-bash-variable-when-piping-to-function