在下面的示例中,我们设置了数组变量 - files_in_array,其中包含在/tmp 下捕获的所有 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 脚本中使用数组之前是否必须清除数组?
最佳答案
与变量数组一样,数组是在 shell 进程环境中定义的,与变量不同,它们不能导出以供子进程访问。
你发出的第一个命令
files_in_array=( $( find /tmp -type f -name '*.xml' ) )
初始化数组,如果 files_in_array 包含数据,它将被清除。
正如评论中所说,这不是一种像您那样初始化数组的安全方法,因为在进程扩展 $(..)
之后,结果被拆分为空格、制表符和换行符,并且文件名可能是拆分成元素,一种安全的方法是使用 glob 文件扩展,因为它发生在之后并且不会拆分。
所以只是
files_in_array=( /tmp/*.xml )
获取所有子路径
shopt -s globstar
shopt -s nullglob
files_in_array=( /tmp/**/*.xml )
bash 4.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 )
关于arrays - 在这种情况下我们需要在 bash 脚本中清除数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48319676/