3

I want to use the aruments from the xargs as the index of this array, this is the scripts:

1 #!/bin/bash
2 array[0]=x
3 array[1]=y
4 echo array : ${array[0]}, ${array[1]}
5 echo -n {0..1} | xargs -I index -d" " echo index,${array[index]}

and this is the output:

[usr@linux scripts]$ sh test.sh 
array : x, y
0,x
1,x 

you can see that the array can not accept the index correctly, it's always the first. How can I get this kind of output:

array : x, y
0,x
1,y

I showed the example with the command echo, however, my real aim is for another command, like this :

echo -n {0..1} | xargs -I index -d" " somecommand ${array[index]}

so that I want a general solution of this question.
And I also tried the parallel instead of the xargs, it's have the same problem.

spring cc
  • 937
  • 1
  • 10
  • 19
  • 2
    This can't possibly work the way you want, because the array only exists in the shell and `xargs` works by creating child processes. The `${...}` stuff in the xargs command line is expanded only once, before xargs is executed. You'll have to either make the array available to child processes, or rewrite the xargs as a shell loop. –  Oct 19 '16 at 10:43
  • @WumpusQ.Wumbley OK, however, I want to use the `xargs` to do parallel, so a shell loop could not be a proper solution :( – spring cc Oct 19 '16 at 11:15
  • You could try to put the array as a list in the environment and use that in the command started with `xargs`, but there could be corner cases... – Serge Ballesta Oct 19 '16 at 13:49

2 Answers2

1
for i in `seq 0 $[${#array[@]}-1]`;do echo $i,${array[$i]};done|xargs -n1 echo
Ipor Sircer
  • 3,069
  • 3
  • 10
  • 15
  • 1
    yes, it's a away to avoid this kind of problem. However, your scripts should be corrected a little: `for i in \`seq 0 \`expr ${#array[@]}-1\`\`` – spring cc Oct 19 '16 at 12:36
1

With GNU Parallel you can do:

#!/bin/bash

. `which env_parallel.bash`

array[0]=x
array[1]=y
echo array : ${array[0]}, ${array[1]}
echo -n {0..1} | env_parallel -d" " echo '{},${array[{}]}'
# or
echo -n {0..1} | env_parallel --env array -d" " echo '{},${array[{}]}'

Your problem boils to exporting arrays, which you cannot do without cheating: Exporting an array in bash script

Community
  • 1
  • 1
Ole Tange
  • 31,768
  • 5
  • 86
  • 104