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
Delete file/folder
1 2 |
#!/bin/bash rm ‘/path to the file or 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
Delete contents of a folder
1 2 |
#!/bin/bash rm ‘/path to the 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.