In a bash function, I want to list all the files in a given folder which correspond to a given set of file types. In pseudo-code, I am imagining something like this:
getMatchingFiles() {
output=$1
directory=$2
shift 2
_types_=("$@")
file_array=find $directory -type f where-name-matches-item-in-_types_
# do other stuff with $file_array, such as trimming file names to
# just the basename with no extension
eval $output="${file_array[@]}"
}
dir=/path/to/folder
types=(ogg mp3)
getMatchingFiles result dir types
echo "${result[@]}"
For your amusement, here are the multiple workarounds, based on my current knowledge of bash, that I am using to achieve this. I have a problem with the way the function returns the array of files: the final command tries to execute each file, rather than to set the output parameter.
getMatchingFiles() {
local _output=$1
local _dir=$2
shift 2
local _type=("$@")
local _files=($_dir/$_type/*)
local -i ii=${#_files[@]}
local -a _filetypes
local _file _regex
case $_type in
audio )
_filetypes=(ogg mp3)
;;
images )
_filetypes=(jpg png)
;;
esac
_regex="^.*\.("
for _filetype in "${_filetypes[@]}"
do
_regex+=$_filetype"|"
done
_regex=${_regex:0:-1}
_regex+=")$"
for (( ; ii-- ; ))
do
_file=${_files[$ii]}
if ! [[ $_file =~ $_regex ]];then
unset _files[ii]
fi
done
echo "${_files[@]}"
# eval $_output="${_files[@]}" # tries to execute the files
}
dir=/path/to/parent
getMatchingFiles result $dir audio
echo "${result[@]}"
file_array=find $directory -type f where-name-matches-item-in-_types_will just assign the string to file array, nothing is being executed.