简体   繁体   English

bash将命令的输出存储在数组中

[英]bash store output of command in array

I'm trying to find if the output of the following command, stores just one file in the array array_a 我正在尝试查找以下命令的输出是否仅在数组array_a中存储一个文件

array_a = $(find /path/dir1 -maxdepth 1 -name file_orders?.csv)
echo $array_a
/path/dir1/file_orders1.csv /path/dir1/file_orders2.csv
echo ${#array_a[@]}
1

So it tell's me there's just one element, but obviously there are 2. If I type echo ${array_a[0]} it doesn't return me anything. 因此,它告诉我只有一个元素,但显然有2个元素。如果我键入echo $ {array_a [0]},它什么也不会返回。 It's like, the variable array_a isn't an array at all. 就像变量array_a根本不是一个数组。 How can i force it to store the elements in array? 我如何强制它将元素存储在数组中?

You are lacking the parentheses which define an array. 您缺少定义数组的括号。 But the fundamental problem is that running find inside backticks will split on whitespace, so if any matching file could contain a space, it will produce more than one element in the resulting array. 但是根本的问题是,反引号内部的运行find会在空格上分割,因此,如果任何匹配的文件可以包含一个空格,它将在结果数组中产生多个元素。

With -maxdepth 1 anyway, just use the shell's globbing facilities instead; 无论如何使用-maxdepth 1 ,只需使用shell的globbing设施即可; you don't need find at all. 您根本不需要find

 array_a=(/path/dir1/file_orders?.csv)

Also pay attention to quotes when using the array. 使用数组时也要注意引号。

 echo "${array_a[@]}"

Without the quotes, the whitespace splitting will happen again . 没有引号,空格将再次发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM