Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store command return values in bash array

Tags:

arrays

bash

I have a command which upon execution return me set of numbers which I want to store in a bash array.

    vihaan@trojan:~/trash$ xdotool search brain 
Defaulting to search window name, class, and classname
52428804
50331651
62914564
65011896
48234499

How do I store these values in an array ?

like image 361
Vihaan Verma Avatar asked Aug 21 '13 19:08

Vihaan Verma


People also ask

How do you store the output of a command in an array?

The <(COMMAND) is called process substitution. It makes the output of the COMMAND appear like a file. Then, we redirect the file to standard input using the < FILE. Thus, the readarray command can read the output of the COMMAND and save it to our my_array.

How do you store results of command in a variable?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]


2 Answers

In this simple case:

array=( $(xdotool search brain) )

If the output were more complicated (for example, the lines might have spaces in them), you can use the bash builtin mapfile:

mapfile -t array < <(xdotool search brain)

(help mapfile for more information)

like image 99
rici Avatar answered Oct 06 '22 23:10

rici


declare -a myarr  # declare an array
myarr=($(grep -v "Defaulting" $(xdotool search brain) | awk '{printf $1" "}'))  # Fill the array with all the numbers from the command line
echo ${myarr[*]}  # echo all the elements of the array

OR

echo ${myarr[1]}  # First element of the array
like image 32
iamauser Avatar answered Oct 07 '22 01:10

iamauser