I am trying to search files starting with the name properties.* inside a directory and assign to an array. When I try to print the array outside the loop, it shows empty. Inside the do loop, it prints fine. How will make this array global or take the values outside the loop. Please share your thoughts.

find /opt/scripts/ -type f -name "properties.*" | while read FILES
   x=$(( $x + 1 ))
   echo ${NAMES[@]}

Recommended Answers

All 2 Replies

It's because when bash creates a subshell for the pipe. A new variable is created in this subshell, updated on each iteration and then discarded when the subshell terminates. The simplest answer is probably to use ksh.

names=( $(find /opt/scripts/ -type f -name "properties.*") )
IFS=$' \t\n'
printf "%s\n" "${names[@]}"
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.