When managing your files and directories in the command line, it's often useful to identify large directories that may be consuming a significant amount of storage space. This custom shell function, find-large-dirs()
, allows you to search for directories larger than a specified size.
You can add the find-large-dirs()
function to your shell configuration files (.bashrc
, .bash_profile
, or .zshrc
) to make it available every time you start a new terminal session. Follow these steps to add and use the function in your shell configuration:
-
Open Visual Studio Code or your preferred code editor.
-
For Bash (
.bashrc
or.bash_profile
) and Zsh (.zshrc)
:a. Bash Configuration: If you're using Bash, open your Bash configuration file. Depending on your system, it might be either
~/.bashrc
or~/.bash_profile
.b. Zsh Configuration: If you're using Zsh, open your Zsh configuration file, which is typically
~/.zshrc
. -
Copy and Paste: Copy and paste the following shell function at the end of your configuration file:
# Function to find directories larger than a specified size find-large-dirs() { local size_arg="${1:-500M}" # Default size is 500M if not provided if [[ ! "$size_arg" =~ ^[0-9]+[BbKkMmGg]$ ]]; then echo "Invalid size format. Please use B, K, M, or G suffix (case-insensitive)." return 1 fi find . -type d -exec du -sh {} + | awk -v size_arg="$size_arg" ' function convert_to_bytes(size) { if (size ~ /[0-9]+[Bb]$/) return size + 0 if (size ~ /[0-9]+[Kk]$/) return size * 1024 if (size ~ /[0-9]+[Mm]$/) return size * 1024 * 1024 if (size ~ /[0-9]+[Gg]$/) return size * 1024 * 1024 * 1024 return 0 } { size = convert_to_bytes($1) if (size > convert_to_bytes(size_arg)) { size_str = sprintf("%.0f", size) print size_str "\t" $0 } }' | sort -n | cut -f2- }
-
Save the Changes: Save the changes to your configuration file.
-
Reload the Configuration:
-
For Bash: In your terminal, either restart your terminal or run:
source ~/.bashrc
-
For Zsh: In your terminal, either restart your terminal or run:
source ~/.zshrc
-
-
Usage: You can now use the
find-large-dirs
function in your Bash or Zsh shell. For example, to find directories larger than 1 gigabyte:find-large-dirs 1G
By adding the find-large-dirs
function to your shell configuration, you can easily identify large directories in your command-line environment, regardless of whether you use Bash or Zsh. This custom function is a valuable tool for managing disk space and organizing your files and folders more efficiently.