0

I have an empty array

arr=()

Can I use xargs to append elements to this array?

Like this:

echo "test" | xargs arr+=()
1
  • 1
    not like that, but there are other ways. The question is just what format your input is. Remember xargs treats quotes specially, and in ways that are not fully compatible with the shell's syntax.
    – ilkkachu
    Jul 27, 2021 at 18:53

2 Answers 2

2

No, that's not possible to do. The xargs tool executes an external utility once or many times depending on the amount of input that it gets. An array assignment is most likely not the name of an external utility, so it will fail to run. Additionally, since the xargs tool itself is an external utility, it has no way to change anything in the current shell's environment.

It would be easier to do just

arr+=( test )

or, if you want to read from a command into an array (one element per line of output from the command):

readarray -t -O "${#arr[@]}" arr < <( some_command )

This starts adding new element to the end of the array arr, reading each line from the output of some_command as a new array element. It's the -O option that determines at what offset in the array the data gets inserted, and "${#arr[@]}" will expand to the length of the array arr. We will therefore insert data beginning just after the current end of the array arr. The effect is that elements get appended to the array.

Testing the former command:

$ arr=( 1 2 3 )
$ readarray -t -O "${#arr[@]}" arr < <( printf 'a\nb\nc\n' )
$ printf '%s\n' "${arr[@]}"
1
2
3
a
b
c

In this example, I start with an array containing the three elements 1, 2, and 3, just to illustrate that the elements are appended. The array may also be empty at the start.

If the array is known to be empty, or if you want to replace the elements in the array, then use the command without the -O option:

readarray -t arr < <( some_command )

The above command would replace all elements of the arr array with elements taken from the lines of output of the some_command command.

See also help mapfile and the bash manual (the readarray command and the mapfile command are identical).

1

When a Parent Process (eg Bash) starts a Child Process (eg xargs) , the Child Process gets a copy of the environment (including array variable arr) and this Process can update that environment, but when it exits, this environment is not passed back to the Parent Process.
So the answer to your question, in general, is NO.

More to the Point, xargs has no way to update environment variables and it only executes other commands.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.