How can I run a command from a bash script and at end print the number of lines it printed?
The awk equivalent would be
{ print; }
END { print NR; }
I could only come up with the following. This works for now, but I can not get it outside the subshell.
| (lc=0; while read; do echo $REPLY; lc=$(($lc+1)); done; echo $lc)
UPDATE
Seems my problem was something quite different. I had first tried to use /dev/stdout
which failed:
tester> { echo abc | tee /dev/stdout | wc -l; } > /tmp/abc; cat /tmp/abc
2
This seemed to be because tee /dev/stdout
gives error:
tester> echo abc | tee /dev/stdout
tee: /dev/stdout: Permission denied
abc
The answer by Jeff Schaller worked:
tester> { echo abc | tee >(wc -l); } > /tmp/abc; cat /tmp/abc
abc
1
But this morning on retrying I saw it works!
tmp> echo abc | tee /dev/stdout
abc
abc
After spending some time I found two problems:
When |tee /dev/stdout
failed yesterday I had logged in as usr1 done a sudo to another usr2, sudo su usr2
. In this case the chain of soft link is /dev/stdout -> /proc/self/fd/1 -> /dev/pts/1
and the last one was owned by usr1
. So the tee
failed. Today I tried as usr1, so it succeeded.
But then I realized the other error with tee /dev/stdout
, which is that all output goes to wc -l
; line count is double and nothing is printed.
tee
to no avail, but there's this ugliness:do_stuff > output; (cat output; wc -l output; rm -f output)
.