简体   繁体   中英

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.

Say I want all folders and subfolder's files in /home/documents/ it will give me the array of files at the end.

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. Please Help.

First off, generally, you don't want to parse the output of 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.

Next we have

ar=()

() Creates an array. The input to this array is now going to be the output of the find command. So when we put them together we end up with "Create an array from the output of this find command".

The rest of the command is just showing that ar is actually an array. We print out the length of the array and then the value at index 2.

Suggested Googling would be... command substitution in bash. Making an array from a command in bash. How to use arrays in 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 . Also i suggest reading the man page of find since "." and ".." may appear in your array as it is written now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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