Solved Shellscript appending array values

Solved issue

banderas20

Active Member
Joined
Aug 1, 2018
Messages
133
Reaction score
50
Credits
1,056
Hi,

I'm developing a shellscript which searches through an specific directory and stores filenames in 3 arrays (files1, files2 and files3).
I have 3 dates to search through (date1, date2, and date3)

Code:
files1=$(ls -1 filename_$date1*.txt 2>/dev/null)
files2=$(ls -1 filename_$date2*.txt 2>/dev/null)
files3=$(ls -1 filename_$date3*.txt 2>/dev/null)

Then I append the 3 arrays in a single one as follows:

Code:
filesTotal=( "${files1[@]}" "${files2[@]}" "${files3[@]}")

However, when I iterate through "filesTotal", I get something like this:

Code:
file1.txt

file2.txt file3.txt

That is,
  • A single file with the contents of the first array.
  • An empty value, because second array has nothing.
  • file2.txt and file3.txt (side by side)

I was expecting something like this:

Code:
file1.txt
file2.txt 
file3.txt

I mean, empty value removed and all the names formatted in a single column.

¿can you help me out?

Thanks!
 


The issue you're encountering is due to the way you're assigning the output of the ls command to the arrays. When you use $(ls -1 filename_$date1*.txt 2>/dev/null), it assigns the entire output as a single string rather than an array of filenames.

To fix this, you can use mapfile (or readarray in some systems) to read the filenames into arrays properly.

This should work I think.
Code:
# Read filenames into arrays
mapfile -t files1 < <(ls -1 filename_$date1*.txt 2>/dev/null)
mapfile -t files2 < <(ls -1 filename_$date2*.txt 2>/dev/null)
mapfile -t files3 < <(ls -1 filename_$date3*.txt 2>/dev/null)

# Combine arrays into a single array
filesTotal=( "${files1[@]}" "${files2[@]}" "${files3[@]}" )

# Iterate through the combined array and print each filename on a new line
for file in "${filesTotal[@]}"; do
    echo "$file"
done
 
Hi.

I removed the double quotes

From:

Code:
filesTotal=( "${files1[@]}" "${files2[@]}" "${files3[@]}")

To:

Code:
filesTotal=( ${files1[@]} ${files2[@]} ${files3[@]})

And everything worked as expected.

I'll take a look at your comments, though.

Many thanks!
 

Staff online

Members online


Top