# Remove Files from Linux: Automated Scripting for IT Admins

Maintaining organized and secure filesystems across a fleet of remote Linux devices is a critical task for system administrators. Manually connecting to individual endpoints to remove redundant folders or temporary files is inefficient and introduces unnecessary security risks.

This guide provides a streamlined, automated framework for managing files on Linux distributions, including Ubuntu, RHEL, CentOS, and Debian. By leveraging [customized scripts](https://www.hexnode.com/mobile-device-management/help/how-to-create-and-execute-custom-scripts-on-linux/?utm_source=hexnodemdm&utm_medium=manage&utm_campaign=linux_execute_scripts/), administrators can remotely identify and remove specific files or directories across all enrolled devices. This non-invasive approach ensures that all Linux systems managed by the Hexnode portal remain optimized and compliant without requiring manual terminal access or direct SSH intervention.

 Disclaimer: 
The sample scripts provided below are adapted from third-party open-source sites.

 

Automated Remediation: Filesystem Cleanup Scripts
-------------------------------------------------

The below scripts utilize standard Linux utilities for cleanup operations.

**Script Characteristics:**

- **Idempotency:** The script uses conditional logic to verify the existence of the target path before initiating the rm (remove) command.
- **Administrative Inputs:** Administrators define the operation scope by manually populating the ***files*** and ***folders*** arrays within the script body with specific filenames including extensions and folder names prior to deployment.

 Note: 
Administrators can facilitate the deployment of these scripts by utilizing the **Execute Custom Script** action, located within the [Automate](https://www.hexnode.com/mobile-device-management/help/automate-device-management-tasks/) tab of the Hexnode UEM portal. This centralized feature allows for seamless automation of filesystem remediation across the entire managed device fleet.

 

### 1. Target File Deletion

Use this script to remove specific files (e.g., *old\_installer.sh*) or categories of files (e.g., *\*.pdf*).

Bash script to delete files on Linux device

\#!/bin/bash # Add all filenames (with extension) you want to delete files=("Enter file names with extension") # eg: files=("sample.pdf" "wallpaper.jpg") echo "Searching and deleting the following files:" printf '%s\\n' "${files\[@\]}" echo "" for filename in "${files\[@\]}"; do echo "Processing: $filename" matches=$(find / -type f -name "$filename" 2>/dev/null) if \[ -z "$matches" \]; then echo "File not found: $filename" else echo "$matches" | while read -r file; do rm -f "$file" echo "Deleted: $file" done fi echo "" done echo "Operation completed."

   1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

  \#!/bin/bash

\# Add all filenames (with extension) you want to delete

files=("Enter file names with extension") \# eg: files=("sample.pdf" "wallpaper.jpg")

echo "Searching and deleting the following files:"

printf '%s\\n' "${files\[@\]}"

echo ""

for filename in "${files\[@\]}"; do

 echo "Processing: $filename"

 matches=$(find / -type f -name "$filename" 2>/dev/null)

 if \[ -z "$matches" \]; then

 echo "File not found: $filename"

 else

 echo "$matches" | while read -r file; do

 rm -f "$file"

 echo "Deleted: $file"

 done

 fi

 echo ""

done

echo "Operation completed."

   

 

  

![](https://cdn.hexnode.com/mobile-device-management/help/wp-content/uploads/2026/02/Linux-script-to-delete-files-portal-output--300x149.png%22%20alt=)

### 2. Recursive Folder Deletion

Use this script to remove entire directories and all their contents (e.g., *sample folder*).

Bash script to delete folders on Linux device

\#!/bin/bash # Add all folder names you want to delete folders=("Enter folder names") # eg: folders=("sample folder" "test") echo "Searching and deleting the following folders:" printf '%s\\n' "${folders\[@\]}" echo "" for foldername in "${folders\[@\]}"; do echo "Processing folder: $foldername" matches=$(find / -type d -name "$foldername" 2>/dev/null) if \[ -z "$matches" \]; then echo "Folder not found: $foldername" else echo "$matches" | while read -r dir; do rm -rf "$dir" echo "Deleted folder: $dir" done fi echo "" done echo "Operation completed."

   1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

  \#!/bin/bash

\# Add all folder names you want to delete

folders=("Enter folder names") \# eg: folders=("sample folder" "test")

echo "Searching and deleting the following folders:"

printf '%s\\n' "${folders\[@\]}"

echo ""

for foldername in "${folders\[@\]}"; do

 echo "Processing folder: $foldername"

 matches=$(find / -type d -name "$foldername" 2>/dev/null)

 if \[ -z "$matches" \]; then

 echo "Folder not found: $foldername"

 else

 echo "$matches" | while read -r dir; do

 rm -rf "$dir"

 echo "Deleted folder: $dir"

 done

 fi

 echo ""

done

echo "Operation completed."

   

 

  

![](https://cdn.hexnode.com/mobile-device-management/help/wp-content/uploads/2026/02/Linux-script-to-delete-files-portal-output--300x149.png%22%20alt=)

Script Execution steps
----------------------

Save the above codes as a **.sh** file and deploy it using the [Execute Custom Script](https://www.hexnode.com/mobile-device-management/help/how-to-create-and-execute-custom-scripts-on-linux/?utm_source=hexnodemdm&utm_medium=manage&utm_campaign=linux_execute_scripts/) action available within the Hexnode UEM portal.

Executing a custom script via Hexnode UEM - Quick steps

1. Go to **Manage** > **Devices** > Select your Linux device.
2. Select **Actions > Execute Custom Script**.
3. Upload the .sh file and click **Execute**.

 

 

Verifying the results
---------------------

Upon execution, Hexnode UEM captures the script’s terminal output and centralizes the data within the portal for administrative review. This remote verification process allows you to confirm the successful removal of specific files or directories without requiring direct access to the device’s filesystem.

To review the cleanup status, follow these steps within the Hexnode portal:

1. Navigate to the **Manage** tab and select the specific device.
2. Go to the **Action History** sub-tab to view a chronological log of all recent remote actions.
3. Locate the entry for the cleanup script (e.g., file delete.sh or folder delete.sh) and click the **Show Output** button.

The output window provides a real-time summary of the operation:

- **Target Identification:** The log lists the specific files (e.g., sample.pdf) or folders (e.g., test folder) targeted for deletion.
- **Processing Status:** For each item, the console confirms the absolute path and status, such as “Deleted: /home//Downloads/sample.pdf”.
- **Execution Confirmation:** A final “Operation completed” message and an **Exit Code: 0** signify a successful execution with no errors.

Operational Scenarios for Automated Filesystem Remediation
----------------------------------------------------------

By leveraging **Hexnode UEM’s Execute Custom Script** capability, administrators can transform basic scripting into a powerful, scalable infrastructure management tool. The following matrix outlines the strategic scenarios where these filesystem remediation scripts provide maximum business impact and operational security across your Linux fleet.

ScenarioHexnode Strategic ActionBusiness Impact**Security Hygiene**Deploy the script to remove unauthorized scripts files or known “indicators of compromise” (IoCs). **Risk Mitigation:** Prevents potential security breaches by removing malicious files before they are executed.**Disk Space Recovery**Target large, legacy application cache folders or temporary build directories.Hardware Optimization: Extends the life of SSDs and prevents system crashes due to “Disk Full” errors.**Compliance & Privacy**Permanently delete folders containing PII (Personally Identifiable Information) on shared or decommissioned devices.**Regulatory Compliance:** Ensures adherence to GDPR, HIPAA, or SOC2 data-retention policies.**Software De-provisioning**Clean up residual configuration folders left behind after an uninstallation.**System Stability:** Ensures a “clean slate” for future software deployments.Operational Best Practices
--------------------------

- **Permanent Action:** Data deleted via ***rm*** is not sent to a Trash folder. It is gone immediately.
- **Root Privileges:** Hexnode executes these scripts with **Root (sudo)** authority. This allows the script to clean up system-level directories that standard users cannot access.
- **Scoped Searching:** To speed up the process, replace the ***/*** in the find command with a specific path (e.g., */var/log* or */home/user*) to limit the search area.

 Notes:- The script can be executed without providing any arguments.
- 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.

 

Frequently Asked Questions
--------------------------

#### 1. Does the script handle multiple files at once? 

Yes. You can add as many filenames in the parentheses, separated by spaces: files= (“test.txt” “data.tmp” “log\_01.log”).

#### 2. What happens with the Filesystem Cleanup Scripts if the file is not found on the device? 

The ***rm*** command will return an error message in the output saying the file was not found, which you can review in the Hexnode console.