How to send array elements to stdin of a command?

I have a command that can receive a list of file paths, newline separated, from stdin. I have these file paths stored in an array. How should I send the array elements to the command?

I have used the following, but have a vague feeling that I'm not doing it efficiently:

files=("/first/file" "/second/file" "/some/directory" "/file/with spaces")
for i in "${places[@]}" ; do echo "$i" ; done | command ...

1 Answer

I prefer printf:

printf "%s\n" "${array[@]}" | ...

You can also use IFS to join array elements using a character:

(IFS=$'\n'; echo "${array[*]}") | ...

The difference between "${array[@]}" and "${array[*]}" is that the former expands to the array elements as separate words, the latter expands to a single word formed by joining the array elements using the first character of IFS.

4

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like