In specific scenarios, there is often a need to eliminate deep folders, for example when we are managing a monorepo and we would like to clean some files in every package, as node_modules
or dist
. Or, simply, you want to free up disk space.
This process can be automatized implementing a Shell script, available in Unix
and Linux
systems (also in Git Bash
).
find . -name \"node_modules\" -type d -prune -exec rm -rf '{}' +
-
find .
: Searches for files and directories in a file system. In this case, the dot.
indicates the current directory. -
-name "node_modules"
: Specifies to search for items with the namenode_modules
. -
-type d
: Indicates that only directories (folders) should be searched. -
-prune
: Stops the search in the matching directories, meaning it will not descend further into those directories. -
-exec rm -rf '{}' +
: This segment executes therm -rf
command on the results found by find.rm
is the command for removing files or directories, and the options-rf
mean “recursively” and “forcefully” (without asking for confirmation).'{}'
is a placeholder thatfind
will replace with the found file path.+
indicatesfind
that multiple results can be passed to the command in a single execution.
Then, in our root package.json
we can add a script
:
{ "scripts": { "clean:node_modules": "find . -name \"node_modules\" -type d -prune -exec rm -rf '{}' +", "clean:dist": "find . -name \"dist\" -type d -prune -exec rm -rf '{}' +" }}
This simple Shell script allows you to clean files in your monorepo. Also, it will function in any folder, providing the flexibility to execute it wherever you choose!
Happy coding! 🚀