Files
bash_snippets/check_folder_for_extension.sh
swg 9d0e0162eb apply style guide
Applied [Google Shell Scripting Style Guide](https://google.github.io/styleguide/shellguide.html) to the check_folder snippet.
fixed naming bug of filesnpaths variable.
2023-11-21 08:18:31 +00:00

51 lines
1.5 KiB
Bash
Executable File

#!/bin/bash
## Checks given folder for files with certain extensions. Subfolders are checked recursively.
## $1 Folder to check.
## $2 space separated list of extensions to check for. e.g.: "*.jpg *.JPG *.mp4 *.MP4".
## returns Count of files found with the desired extension.
function check_folder() {
local _folder=$1;
local _extensions=$2;
local _file_count=0;
if [ -d "$_folder" ]; then # is a folder
local _item="";
local _fc=${#Files_N_Paths[@]};
pushd "$_folder" 1>/dev/null;
for _item in ${_extensions}; do # lookup all files with the desired extensions
if [[ -f "$_item" ]]; then # is a file
Files_N_Paths[$_FC]="$(pwd)/$_item";
((_fc+=1));
((_file_count+=1));
fi
done
# check subfolders if exist
local _sub_folders="$(/usr/bin/ls . 2>/dev/null)";
local _cnt=0;
for _sub_item in ${_sub_folders}; do
if [[ -d "$_sub_item" ]]; then
check_folder "$_sub_item" "$_extensions";
_cnt=$?
((_file_count+=_cnt));
fi
done
popd 1>/dev/null;
fi
return $_file_count
}
## Test the check_folder() function with local test folder and images.
function test() {
local _my_folder="./cffe_test";
check_folder $_my_folder "*.jpg *.JPG" # space separated list for multiple extensions!
local _files_count=$?
echo "Found $_files_count files in folder $_my_folder, length of files array is ${#Files_N_Paths[*]}.";
for ((_fc=0;_fc<${#Files_N_Paths[*]};_fc++)); do
echo "$_fc : ${Files_N_Paths[$_fc]}";
done
}
declare -A Files_N_Paths;
test