在下面的示例中,我们设置数组变量-files_In_array,其中包含在/tmp下捕获的find命令的所有xml文件
注意-我们使用第二个“(”)创建数组

files_in_array=( $( find /tmp -type f -name '*.xml' ) )

所以现在我们可以捕捉第一个/第二个值。。等,如下
echo ${files_in_array[0]}

/tmp/demo_values.xml


echo ${files_in_array[1]}

/tmp/prod_values.xml

直到现在一切都很完美
但我不确定我们是否需要
 files_in_array=()

所以,在bash脚本中使用数组之前,必须清除该数组吗?

最佳答案

Like变量数组是在shell进程环境中定义的,与变量不同,它们不能导出以在子进程中访问。
你发出的第一个命令

files_in_array=( $( find /tmp -type f -name '*.xml' ) )

初始化数组如果数组中的文件包含数据,它将被清除。
如注释中所述,这不是一种安全的初始化数组的方法,因为在进程扩展$(..)之后,结果将被拆分到空格选项卡和换行符上,并且文件名可能被拆分为elemnts,一种安全的方法是使用glob file扩展,因为它发生在且不被拆分之后。
所以只是
files_in_array=( /tmp/*.xml )

获取所有子路径
shopt -s globstar
shopt -s nullglob
files_in_array=( /tmp/**/*.xml )

在Bash4.0之前
正如评论中所说,globstar是在bash 4.0中引入的,在此之前,另一种方法是使用find-print0
files_in_array=(  )
while IFS= read -d '' -r file; do
    files_in_array+=( "$file" )
done < <( find /tmp -type f -name '*.xml' -print0 )

10-06 15:08
查看更多