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.

3
  • 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. Commented Oct 19, 2016 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 :( Commented Oct 19, 2016 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... Commented Oct 19, 2016 at 13:49

2 Answers 2

1
for i in `seq 0 $[${#array[@]}-1]`;do echo $i,${array[$i]};done|xargs -n1 echo 
Sign up to request clarification or add additional context in comments.

1 Comment

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``
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.