10

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 ?

3 Answers 3

18

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)

Sign up to request clarification or add additional context in comments.

Comments

4
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

1 Comment

The grep -v is harmless but unnecessary: that line is sent to stderr, not stdout. You shouldn't use printf in awk when you mean print for the same reason you shouldn't do that in C: there might be a percent in the string.
0

You could write another command the expects input and puts said input into an array. So you would pipe the output from the first command to your toArray command. Then do what you need to with the toArray output.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.