在这种情况下,我们需要在bash脚本中清除数组

时间:2018-01-18 10:57:44

标签: arrays linux bash

在下面的示例中,我们设置了数组变量 - files_in_array ,所有xml文件都找到了在/ tmp

下捕获的命令

注意 - 我们使用第二个“(”“)”来创建数组

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脚本中的数组之前,我们是否必须清除数组?

1 个答案:

答案 0 :(得分:1)

类似变量数组是在shell进程环境中定义的,与变量不同,它们无法导出以便在子进程中访问。

你提供的第一个命令

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

如果files_in_array包含数据,则初始化数组,它将被清除。

正如评论中所述,这不是一种以您的方式初始化数组的安全方法,因为在进程扩展$(..)之后,结果会在空格选项卡和换行符上拆分,并且文件名可能会被拆分为elemnts,这是一种安全的方式是使用glob文件扩展,因为它发生在分裂之后。 所以只是

files_in_array=( /tmp/*.xml )

获取所有子路径

shopt -s globstar
shopt -s nullglob
files_in_array=( /tmp/**/*.xml )
在bash 4.0之前

正如评论中所述,在bash 4.0中引入了globstar,在此之前用find -print0

执行此操作
files_in_array=(  )
while IFS= read -d '' -r file; do
    files_in_array+=( "$file" )
done < <( find /tmp -type f -name '*.xml' -print0 )