Bash Listing Files in a Directory and Testing whether Specific Files Exist in Directories: Difference between revisions
Jump to navigation
Jump to search
m (Ovidiu moved page Bash Listing Files in a Directory to Bash Listing Files in a Directory and Testing whether Specific Files Exists in Directories without leaving a redirect) |
|
(No difference)
|
Revision as of 23:26, 1 February 2022
Internal
Overview
To list files:
local dir=...
for f in ${dir}/*; do
[[ -f ${f} ]] && echo -n "$(basename ${f}) "
done
To list directories, replace -f with -d.
Note that if ${dir} does not exist, or if it exists and there are no files in that directory, f is resolved to the literal "dirname/*".
Multiple directories:
for f in t/master-* t/worker-*; do
[[ -f ${f} ]] && { rm ${f} && info "deleted ${f}" || warn "failed to delete ${f}"; }
done
Variations
find: To further research, it seems the following approach does not work because if there is more than one directory, the first iteration assigns a multi-line to d:
for d in $(find ${dir} -name "*-something" -type d); do
debug "d: ${d}"
...
done
ls: Same for ls, $(ls ...) produces multi-line output.go