简体   繁体   English

Bash脚本将目录/子目录中的所有文件加载到数组中

[英]Bash Script to load all files in a directory/sub-directories into a Array

I am trying to write a script that will load all file names with paths into an array in a bash script. 我正在尝试编写一个脚本,该脚本会将带有路径的所有文件名加载到bash脚本中的数组中。

Say I want all folders and subfolder's files in /home/documents/ it will give me the array of files at the end. 假设我想要/ home / documents /中的所有文件夹和子文件夹的文件,它将在末尾提供文件数组。

My current Script is very basic, but should has some functionality. 我当前的脚本非常基础,但是应该具有一些功能。

num_partitions=0
for file in /home/documents/*; do
  date_partition[$num_partitions]=${file##*/}
  ((num_partitions++))
  echo ${date_partition} 
done

Currently it only prints a black screen. 当前,它仅打印黑屏。 How can I fix it to attain the functionality I need and to print our properly? 如何修复它以获得所需的功能并正确打印我们的图像?

I am new to Bash, this is actually my first Script. 我是Bash的新手,这实际上是我的第一个脚本。 Please Help. 请帮忙。

First off, generally, you don't want to parse the output of ls... http://mywiki.wooledge.org/ParsingLs 首先,通常,您不想解析ls的输出... http://mywiki.wooledge.org/ParsingLs

Next, The logic of your approach isn't wrong. 接下来,您的方法的逻辑没有错。 There is an easier method that we can use to accomplish this task though! 不过,有一种更简单的方法可以用来完成此任务!

ar=( $(find /home/documents/*) ); echo "${#ar[@]}"; echo "${ar[2]}"

Breaking it down we have. 分解我们有。

$( find /home/documents/* )

This is a command substitution. 这是命令替换。 It captures the output of the command that is written inside it. 它捕获写入其中的命令的输出。 With this you can do something like output=$( find .) and now output is a variable that contains the results of the find command. 这样,您可以执行类似于output=$( find .) ,现在输出是一个包含find命令结果的变量。

Next we have 接下来我们有

ar=()

() Creates an array. ()创建一个数组。 The input to this array is now going to be the output of the find command. 现在,此数组的输入将成为find命令的输出。 So when we put them together we end up with "Create an array from the output of this find command". 因此,当我们将它们放在一起时,最终得到“从此find命令的输出创建一个数组”。

The rest of the command is just showing that ar is actually an array. 该命令的其余部分仅显示ar实际上是一个数组。 We print out the length of the array and then the value at index 2. 我们先打印出数组的长度,然后打印出索引2处的值。

Suggested Googling would be... command substitution in bash. 建议谷歌搜索是... bash中的命令替换。 Making an array from a command in bash. 用bash中的命令制作数组。 How to use arrays in bash. 如何在bash中使用数组。

NOTE: Realize that the command within the $( ) can include | 注意:请注意, $( )中的命令可以包含| to other commands such as find . | tr -d "." | ./some_other_command 其他命令,例如find . | tr -d "." | ./some_other_command find . | tr -d "." | ./some_other_command find . | tr -d "." | ./some_other_command . find . | tr -d "." | ./some_other_command Also i suggest reading the man page of find since "." 另外,我建议您阅读自“”以来的find手册页。 and ".." may appear in your array as it is written now. 和“ ..”可能会出现在您现在编写的数组中。

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

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