Reputation: 1027
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.
Upvotes: 3
Views: 3035
Reputation: 33685
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
Upvotes: 1
Reputation: 3141
for i in `seq 0 $[${#array[@]}-1]`;do echo $i,${array[$i]};done|xargs -n1 echo
Upvotes: 1