如何在bash数组中存储命令返回值

时间:2021-01-02 19:31:01

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

我有一个命令,在执行时返回我想要存储在bash数组中的数字集。

    vihaan@*:~/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 个解决方案

#1


17  

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:

如果输出更复杂(例如,行中可能有空格),则可以使用bash内置mapfile:

mapfile -t array < <(xdotool search brain)

(help mapfile for more information)

(帮助mapfile了解更多信息)

#2


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

#3


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.

您可以在期望输入中编写另一个命令,并将所述输入放入数组中。因此,您可以将第一个命令的输出传递给toArray命令。然后使用toArray输出执行您需要的操作。

#1


17  

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:

如果输出更复杂(例如,行中可能有空格),则可以使用bash内置mapfile:

mapfile -t array < <(xdotool search brain)

(help mapfile for more information)

(帮助mapfile了解更多信息)

#2


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

#3


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.

您可以在期望输入中编写另一个命令,并将所述输入放入数组中。因此,您可以将第一个命令的输出传递给toArray命令。然后使用toArray输出执行您需要的操作。