1

I was trying to solve this issue using find + xargs but I stuck with another issue

I am try to increasing a count using ((a++)) but not working . I have tried couple of combination of counting a value eg. let a++ a=$[ $a + 1] and so on..

See below Output

rax@ubuntu:~# find ./test/ -mindepth 1 | xargs -I{} -n1 bash -xc "((a++)) ; echo $a {}"
+ (( a++ ))
+ echo 0 ./test/abc1
0 ./test/abc1
+ (( a++ ))
+ echo 0 ./test/abc1/abc
0 ./test/abc1/abc
+ (( a++ ))
+ echo 0 ./test/abc2
0 ./test/abc2
+ (( a++ ))
+ echo 0 ./test/abc3
0 ./test/abc3
+ (( a++ ))
+ echo 0 ./test/abcparent
0 ./test/abcparent

EDIT :- xargs did all in same shell

eg. with pid

rax@ubuntu:~# a=0
rax@ubuntu:~# find ./test/ -mindepth 1 | xargs -L2 -I{}  bash -xc "echo $a {} ;((a++)) ; echo $a $$"
+ echo 0 ./test/abc1
0 ./test/abc1
+ (( a++ ))
+ echo 0 1314
0 1314
+ echo 0 ./test/abc1/abc
0 ./test/abc1/abc
+ (( a++ ))
+ echo 0 1314
0 1314
+ echo 0 ./test/abc2
0 ./test/abc2
+ (( a++ ))
+ echo 0 1314
0 1314
+ echo 0 ./test/abc3
0 ./test/abc3
+ (( a++ ))
+ echo 0 1314
0 1314
+ echo 0 ./test/abcparent
0 ./test/abcparent
+ (( a++ ))
+ echo 0 1314
0 1314
Rahul Patil
  • 24,711

1 Answers1

1

The problem is that your variables are being expanded by bash before find is executed. Because of this $a is expanded to 0, $$ is expanded to the PID of your (login) shell, so the command that is executed by bash -xc is actually:

echo 0 {} ;((a++)) ; echo 0 1314

Here {} is replaced by xargs with the result from find and the value of $a is postincremented, but never printed. Try escaping the variables (as in \$a), or even better, putting the bash -xc arguments in single quotes (') instead of double quotes (") to see that it works.

You will also notice that the other commenters are correct, xargs -n1 (or with -I{}) executes a new shell for each argument, therefore incrementing $a will not work - the incremented value will not be visible to the next invocation of the bash -xc command.

zorlem
  • 625