Add filenames to an array and loop based on that

I have 3 files like below:

CV_REF_DATA_09012021.txt
DB_ONLINE_CL_09012021.txt
DFR_CL_INS_09012021.txt

I want to check if the files are present in /NAS/CFG/ and then add it to an array. It’s not required that all the 3 files are present at all times. So, it can either be 1, 2 or all the 3 files. If there are no files the script should exit saying the same. Next I want to loop based on the array and run a “call” script.

The call script uses the file pattern to check the file count as well. Below code from call script.

NASFilecnt=`find . -type f -name "${CV_REF_DATA}*.txt" | wc -l`

So, how can run the loop based on the above. Please let me know if there are any queries.

How about?

NASFilecnt=`find . -type f -name "${CV_REF_DATA}*.txt"`

# set variable 
filefound="no"

# for loop will only execute if there are entries in the $NASFilecnt variable 
for f in $NASFilecnt
do
    filefound="yes" # inside loop means file found 
    echo "I am now working on $f file ..."
done

# do something based upon $filefound 
if [ "$filefound" == "yes" ]
then
	echo "File found and do_something"
else
  echo "File not found. do_nothing"
fi

Does this help?

Wouldn’t it just be better to run the commands inside the for loop instead ?

yes, that or call the user define function.


Linux sysadmin blog - Linux/Unix Howtos and Tutorials - Linux bash shell scripting wiki