Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a Bash array as input to a command?

Say, for example, I have the following array:

files=( "foo" "bar" "baz fizzle" )

I want to pipe the contents of this array through a command, say sort, as though each element where a line in a file. Sure, I could write the array to a temporary file, then use the temporary file as input to sort, but I'd like to avoid using a temporary file if possible.

If "bar fizzle" didn't have that space character, I could do something like this:

echo ${files[@]} | tr ' ' '\012' | sort

Any ideas? Thanks!

like image 663
splicer Avatar asked Mar 31 '11 18:03

splicer


People also ask

How do you access an array in Bash?

To access elements of array using index in Bash, use index notation on the array variable as array[index].


2 Answers

sort <(for f in "${files[@]}" ; do echo "$f" ; done)
like image 104
Ignacio Vazquez-Abrams Avatar answered Sep 23 '22 19:09

Ignacio Vazquez-Abrams


Yet another solution:

printf "%s\n" "${files[@]}" | sort
like image 20
Gordon Davisson Avatar answered Sep 24 '22 19:09

Gordon Davisson