Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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:

#!/bin/bash

c=0;
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"
done
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 at 17:49

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

1 Answer 1

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 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 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 at 16:02

Your Answer

 
discard

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