Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a bash array with output piped from another command? [duplicate]

Tags:

bash

shell

Is there any way to pipe the output of a command which lists a bunch of numbers (each number in a separate line) and initialize a bash array with those numbers?

Details: This lists 3 changelist numbers which have been submitted in the following date range. The output is then piped to cut to filter it further to get just the changelist numbers.

p4 changes -m 3 -u edk -s submitted @2009/05/01,@now | cut -d ' ' -f 2 

E.g. :

422311 543210 444000 

How is it possible to store this list in a bash array?

like image 930
vivekian2 Avatar asked Jun 09 '09 16:06

vivekian2


People also ask

How do you initialize an array in Bash?

To initialise array with elements in Bash, use assignment operator = , and enclose all the elements inside braces () separated by spaces in between them. We may also specify the index for each element in the array.

How do you store output in an array?

Generally, containers (such as arrays) in computer programming are used to store inputs and work-in-progress; once something has been “output”, it's usually no-longer necessary to have it stored in RAM. If you need to store it long-term, output it to a file instead of to a container in RAM.

What is $@ in Bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.


2 Answers

You can execute the command under ticks and set the Array like,

ARRAY=(`command`) 

Alternatively, you can save the output of the command to a file and cat it similarly,

command > file.txt ARRAY=(`cat file.txt`) 

Or, simply one of the following forms suggested in the comments below,

ARRAY=(`< file.txt`) ARRAY=($(<file.txt)) 
like image 93
nik Avatar answered Sep 19 '22 10:09

nik


If you use bash 4+, it has special command for this: mapfile also known as readarray, so you can fill your array like this:

declare -a a readarray -t a < <(command) 

for more portable version you can use

declare -a a while read i; do   a=( "${a[@]}" "$i" ) done < <(command) 
like image 36
Andrey Starodubtsev Avatar answered Sep 21 '22 10:09

Andrey Starodubtsev