Bash Listing Files in a Directory and Testing whether Specific Files Exist in Directories: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
No edit summary
 
(12 intermediate revisions by the same user not shown)
Line 4: Line 4:


=Overview=
=Overview=
<br>
<br>
<font color=darkkhaki>TODO: reconcile and merge with [[Find#Iterating_over_find_Results_in_Scripts|find &#124; Iterating over find Results in Scripts]].</font>
<br>
<br>


To list files:
To list files:
Line 16: Line 26:


To list directories, replace -f with -d.
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:
<syntaxhighlight lang='bash'>
for f in t/master-* t/worker-*; do
    [[ -f ${f} ]] && { rm ${f} && info "deleted ${f}" || warn "failed to delete ${f}"; }
done
</syntaxhighlight>
=Variations=
<font color=darkgray>
'''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:
<syntaxhighlight lang='bash'>
for d in $(find ${dir} -name "*-something" -type d); do
  debug "d: ${d}"
  ...
done
</syntaxhighlight>
'''ls''': Same for ls, $(ls ...) produces multi-line output.go
</font>
=Verify if Files with Specific Extensions Exist in a Directory=
<syntaxhighlight lang='bash'>
if ls -- *.bats >/dev/null 2>/dev/null; then
  echo "BATS files exist in directory"
else
  echo "BATS files do NOT exist in directory"
fi
</syntaxhighlight>

Latest revision as of 18:55, 14 August 2023

Internal

Overview



TODO: reconcile and merge with find | Iterating over find Results in Scripts.


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


Verify if Files with Specific Extensions Exist in a Directory

if ls -- *.bats >/dev/null 2>/dev/null; then
  echo "BATS files exist in directory"
else
  echo "BATS files do NOT exist in directory"
fi