Category filter

Script to delete files and folders on a 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 command is used to remove directory entries. Some of the options supported with this command are –

-r

Recursive deletion for non-empty directory.

-d

Attempts to remove empty directories.

-f

Force attempts to delete all files.

An example code to recursively delete a folder/file in the directory ‘Desktop/My Files’

rm –rf /Users/username/Desktop/My\ Files

Notes:

  • For the above script to work you need to ensure that the Hexnode agent app has full disk access. Navigate to System Preferences > Security and Privacy > Full Disk Access and grant access to ‘hexnodeagentd’.
  • Specifying the incorrect file/folder name may result in loss of data inadvertently.
  • 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 and folders within the folder.

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

rm –rf /Users/username/Desktop/My\files/*

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 – deletes 1.png and 2.png from the Desktop folder.

rm Desktop/*.png – deletes 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.

  • Sample Script Repository