_listFiles_: use extended regex and return 0 if no files found

This commit is contained in:
Nathaniel Landau
2021-10-24 22:46:22 -04:00
parent 9381be991e
commit d7d6edb003
2 changed files with 19 additions and 4 deletions

View File

@@ -186,6 +186,11 @@ _testListFiles_() {
run _listFiles_ "g" run _listFiles_ "g"
assert_failure assert_failure
} }
@test "_listFiles: fail when no files found" {
run _listFiles_ regex ".*notest[0-9]\.txt" "${TESTDIR}"
assert_failure
}
} }
_testMakeSymlink_() { _testMakeSymlink_() {

View File

@@ -480,12 +480,14 @@ _listFiles_() {
# $2 (Required) - pattern to match # $2 (Required) - pattern to match
# $3 (Optional) - directory (defaults to .) # $3 (Optional) - directory (defaults to .)
# OUTS: # OUTS:
# 0: if files found
# 1: if no files found
# stdout: List of files # stdout: List of files
# NOTE: # NOTE:
# Searches are NOT case sensitive and MUST be quoted # Searches are NOT case sensitive and MUST be quoted
# USAGE: # USAGE:
# _listFiles_ glob "*.txt" "some/backup/dir" # _listFiles_ glob "*.txt" "some/backup/dir"
# _listFiles_ regex ".*\.txt" "some/backup/dir" # _listFiles_ regex ".*\.[sha256|md5|txt]" "some/backup/dir"
# readarray -t array < <(_listFiles_ g "*.txt") # readarray -t array < <(_listFiles_ g "*.txt")
[[ $# -lt 2 ]] && fatal "Missing required argument to ${FUNCNAME[0]}" [[ $# -lt 2 ]] && fatal "Missing required argument to ${FUNCNAME[0]}"
@@ -494,22 +496,30 @@ _listFiles_() {
local _pattern="${2}" local _pattern="${2}"
local _directory="${3:-.}" local _directory="${3:-.}"
local _fileMatch e local _fileMatch e
declare -a _matchedFiles=()
case "${_searchType}" in case "${_searchType}" in
[Gg]*) [Gg]*)
while read -r _fileMatch; do while read -r _fileMatch; do
printf "%s\n" "$(realpath "${_fileMatch}")" _matchedFiles+=("$(realpath "${_fileMatch}")")
done < <(find "${_directory}" -maxdepth 1 -iname "${_pattern}" -type f | sort) done < <(find "${_directory}" -maxdepth 1 -iname "${_pattern}" -type f | sort)
;; ;;
[Rr]*) [Rr]*)
while read -r _fileMatch; do while read -r _fileMatch; do
printf "%s\n" "$(realpath "${_fileMatch}")" _matchedFiles+=("$(realpath "${_fileMatch}")")
done < <(find "${_directory}" -maxdepth 1 -iregex "${_pattern}" -type f | sort) done < <(find "${_directory}" -maxdepth 1 -regextype posix-extended -iregex "${_pattern}" -type f | sort)
;; ;;
*) *)
fatal "_listFiles_: Could not determine if search was glob or regex" fatal "_listFiles_: Could not determine if search was glob or regex"
;; ;;
esac esac
if [[ ${#_matchedFiles[@]} -gt 0 ]]; then
printf "%s\n" "${_matchedFiles[@]}"
return 0
else
return 1
fi
} }
_makeSymlink_() { _makeSymlink_() {