Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a simple bash script and want to count how often a command gets called. Here is a minimal example, the counter is called c and should be 4 at the end:


for a in X Y; do
  for b in 1 2; do
    c="$(( ${c} + 1 ))"
    echo "${a}${b}"
  done #| xargs -L 1 -P 20 echo
  echo "count $c"
echo "--"
echo "final $c"

Works great without xargs (final=4), but when I uncomment the pipe to xargs it counts nothing (final=0). Why?

Expected output: |  This happens with xargs:
X1               |  X1
X2               |  X2
count 2          |  count 0
Y1               |  Y1
Y2               |  Y2
count 4          |  count 0
--               |  --
final 4          |  final 0
share|improve this question

migrated from serverfault.com May 19 '14 at 17:49

This question came from our site for system and network administrators.

up vote 4 down vote accepted

The pipe means that your for loop is happening in a subshell, which doesn't pass $c back to the rest of your program. You'll need to rewrite without the pipe. This StackOverflow question is pretty similar. The <( ) syntax might be your friend here.

share|improve this answer
In this case, I think >( ) is the form wanted. Something like ... done > >(xargs ... ) – Gordon Davisson May 19 '14 at 15:55
xargs.. < <(for..) did not work, fixed it by writing all results to a file first and then calling xargs. But my question here was why, so thanks a lot! – Ikarus May 19 '14 at 15:58
@Gordon, sorry, didn't see your answer before posting, but it doesn't seem to work here, I only get Y1 X2 Y2 and then it hangs, weird. – Ikarus May 19 '14 at 16:02

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.