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 ?
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.
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 ...]
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)
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With