This is a worknote.
Scenario
In a Javascript monorepo, there was a need to:
- delete all dist folders files, not the folders themselfs
- but without touching the .gitignore in the folders
TLDR
dir=$(find ./packages -name "dist" -type d);
for i in $dir; do find $i -type f \( -iname "*" ! -iname ".gitignore" \) -exec rm {} +; done
Solution
- Find all
dist
folders in the monorepo - Iterate over the folders set and collect all files within them, excluding .gitignore
- Delete all sets of found files.
Solution Walkthrough
Find all folders with specific name
find ./packages -name "dist" -type d
find
- find - find files. Allow filtering.
./packages
- target root folder to start the search from.
-name "dist"
- filter only object with the name "dist".
-type d
- filter only object with type of directory.
Execute Bash Expression
Exectute an expression in bash and put the results in a local variable.
dir=$()
Find all relevant files in a folder
find $i -type f \( -iname "*" ! -iname ".gitignore" \)
$i
- Variabe containing the folder name from the for
iteration.
-type f
- filter object only of type of file
.
-iname
- From the docs: Like -name
, but the match is case insensitive.
!
- From the docs: !
expr True if expr is false. This character will also usually need protection from interpretation by the shell.
\(
- From the docs: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: \(...\)
instead of (...)
for i in $dir; do find $i -type f \( -iname "*" ! -iname ".gitignore" \); done
Run through folders set and execute find on them
for i in $dir; do find $i; done
for
- for loop
$i
- iteration variable
Execute delete on found set
find $i -exec rm {} +
-exec command {} +
- From the docs: his variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end.
The string {}
is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find.
Top comments (0)