- 10 Oct 2024
- 1 Minute to read
- Print
- PDF
Delete Files/Folders
- Updated on 10 Oct 2024
- 1 Minute to read
- Print
- PDF
Use this script to remotely delete files and/or folders on Linux machines.
Copy and save the contents below to a UTF-8 editor like notepad++ OR Sublime Text in Windows or gedit in Ubuntu.
If you are using notepad++ then use the bottom right panel to change the type to Unix (LF).
Or click here to download the file.
#!/bin/bash # Define the target hostname (convert to lowercase) target_hostname="ENTER_CURRENT_HOSTNAME_OF_DEVICE" # Get the current hostname (convert to lowercase) current_hostname=$(hostname | tr '[:upper:]' '[:lower:]') # Check if the current hostname matches the target hostname if [ "$current_hostname" != "$target_hostname" ]; then echo "Error: Current hostname ($current_hostname) does not match the target hostname ($target_hostname). Exiting." exit 1 fi # Function to delete a file and show a message delete_file() { file_path=$1 if [ -e "$file_path" ]; then rm "$file_path" echo "File $file_path deleted." else echo "File $file_path not found." fi } # Function to delete a folder and its contents and show a message delete_folder() { folder_path=$1 if [ -e "$folder_path" ]; then rm -r "$folder_path" echo "Folder $folder_path and its contents deleted." else echo "Folder $folder_path not found." fi } # DELETE_A_FILE delete_file "/path/to/file.txt" # DELETE_MULTIPLE_FILES delete_file "/path/to/file1.txt" delete_file "/path/to/file2.txt" # DELETE_A_FOLDER_AND_ITS_CONTENTS delete_folder "/path/to/folder" # DELETE_MULTIPLE_FOLDERS_AND_THEIR_CONTENTS delete_folder "/path/to/folder1" delete_folder "/path/to/folder2" # Use caution with wildcards to avoid unintended deletions # For example, this will delete all .txt files in the home directory and its subdirectories # rm -r ~/*.txt
In the script, replace the following placeholder:
Provide the host name in the line:
target_hostname="ENTER_CURRENT_HOSTNAME_OF_DEVICE"Provide the path of the file or folder to be deleted in the lines:
delete_file "/path/to/file.txt"
delete_file "/path/to/file1.txt"
Please use caution with wildcards to avoid unintended deletions, for example, rm -r ~/*.txt will delete all .txt files in the home directory and its subdirectories.
Follow our guide to upload & publish the script using Scalefusion Dashboard.
Note:
Some of the scripts and their contents are sourced from internet and yes, our new friend ChatGPT.
Please validate the scripts on a test machine before deploying them on all your managed devices.
Scalefusion has tested these scripts, however Scalefusion will not be responsible for any loss of data or system malfunction that may arise due to the usage of these scripts.