Category Filter

Script to Delete Files and Folders on Mac

To delete a file or directory on a Mac, the user will have to manually navigate to the location on the Finder application and use the context menu ‘Move to Trash’ option to delete the file. This method is tedious for the device administrator when managing multiple endpoints and impractical when deleting multiple files or folders or doing a batch operation. On the other hand, using a script to automate this process is easy, efficient, and effective. This doc includes a collection of shell scripts that you can run from the Terminal app to delete files or folders on a Mac.

Device admins can remotely run scripts on Macs managed with Hexnode using the Execute Custom Script action.

Scripting Language – Bash

File extension – .sh

Disclaimer:


The Sample Scripts provided below are adapted from third-party Open-Source sites.

Delete file/folder

The rm is used to remove directory entries. Some of the options supported with the command are –

  • -r – Recursive deletion for non-empty directory.
  • -d – Attempt to remove the directory and all files.
  • -f – Force attempt delete of all files.
  • -i – Prompt user to confirm deletion of each file.

An example code to recursively delete user files in the directory ‘Desktop/My Files’ by prompting users –

rm –ri Desktop/My\ Files

The user will be prompted to delete the files one by one. They can confirm with “y” (non-case-sensitive) and decline with “n”.

Notes:

In Bash, before inserting space while defining file or folder names, we use a backslash \ to separate the characters. This will prevent the shell interpreter from interpreting the space as a separator and assuming they were two different arguments. Hence, if the path is New Folder/myFile we write it as New\ Folder/myFile or use single quotes as 'New Folder/myfile' instead.

Delete contents of a folder

Appending the * symbol to the path will select all the contents of the folder. This way you can leave the folder intact but delete all the files/folders within the folder.

Deleting multiple files

You can delete multiple files by simply entering their location one after another separated by a space.

rm Desktop/1.png Desktop/2.png

You can also delete files in batch if they follow a naming pattern or belong to a common extension.

rm Desktop/{1,2}.png – Delete 1.png and 2.png from the Desktop folder.

rm Desktop/*.png – Delete all .png files from the Desktop folder.

Notes:

  • It is recommended to manually validate the script execution on a system before executing the action in bulk.
  • Hexnode will not be responsible for any damage/loss to the system on the behavior of the script.