Category filter
Script to delete files based on size on Mac
Insufficient storage on corporate devices can hinder productivity as it may lead to performance issues for applications and processes. Among other methods to free up device space, administrators may choose to find and delete files larger than a specified size. If files are periodically backed-up to storage resources, deleting larger files from devices running low on storage can be extremely helpful. With Hexnode’s Execute Custom Script action, you can execute the following scripts to identify and remove files based on their size on macOS devices.
Scripting language – Bash
File extension – .sh
List files larger than certain size
You can deploy the following script to list all files present in a folder that are larger than a certain size (in kilobytes).
1 2 3 4 |
#!/bin/bash CurrentUser=$(ls -l /dev/console | awk '/ / { print $3 }') CurrentUserUID=$(id -u "$CurrentUser") launchctl asuser $CurrentUserUID sudo -iu "$CurrentUser" find 'path to folder' -type f -size +'minimum size limit'k -print |
For example, to list all files present at ‘/Users/admin/Desktop/My Documents’ that are larger than 20 kilobytes:
1 2 3 4 |
#!/bin/bash CurrentUser=$(ls -l /dev/console | awk '/ / { print $3 }') CurrentUserUID=$(id -u "$CurrentUser") launchctl asuser $CurrentUserUID sudo -iu "$CurrentUser" find 'Users/admin/Desktop/My Documents' -type f -size +'20'k -print |
Delete files larger than certain size
1 2 3 4 |
#!/bin/bash CurrentUser=$(ls -l /dev/console | awk '/ / { print $3 }') CurrentUserUID=$(id -u "$CurrentUser") launchctl asuser $CurrentUserUID sudo -iu "$CurrentUser" find 'path to folder' -type f -size +'minimum size limit'k -print -delete |
For example, to list and delete all files present at ‘/Users/admin/Desktop/My Documents’ that are larger than 20 kilobytes:
1 2 3 4 |
#!/bin/bash CurrentUser=$(ls -l /dev/console | awk '/ / { print $3 }') CurrentUserUID=$(id -u "$CurrentUser") launchctl asuser $CurrentUserUID sudo -iu "$CurrentUser" find 'Users/admin/Desktop/My Documents' -type f -size +'20'k -print -delete |