bash 如何在bash数组中存储命令返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18365778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to store command return values in bash array
提问by Vihaan Verma
I have a command which upon execution return me set of numbers which I want to store in a bash array.
我有一个命令,它在执行时返回一组我想存储在 bash 数组中的数字。
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 ?
如何将这些值存储在数组中?
回答by rici
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)
(help mapfile
更多信息)
回答by iamauser
declare -a myarr # declare an array
myarr=($(grep -v "Defaulting" $(xdotool search brain) | awk '{printf " "}')) # 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
回答by BrianM
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
输出执行您需要的操作。