When managing a remote server via SSH, you may need to delete files or folders to free up space or remove unnecessary data. The rm (remove) command is used for this purpose. In this tutorial, we will explore different ways to delete files and folders efficiently via SSH.


Basic File Deletion with rm

To delete a specific file, use the following command:

rm myFile.txt

To delete multiple files at once, list them separated by spaces:

rm myFile.txt myFile1.txt myFile2.txt

Instead of listing all files manually, you can use a wildcard * to match multiple files:

rm myFile*.txt

This command will delete all files that start with myFile and end with .txt.


Deleting Folders and Their Contents

To delete a folder and all its contents recursively, use the -r (recursive) flag:

rm -r foldername/

If you want to force the deletion without confirmation, add the -f (force) flag:

rm -rf foldername/

⚠️ Warning: Be careful when using the -rf flag, as it will permanently delete the folder and everything inside it without any confirmation.


Deleting All Files in a Directory (Without Deleting the Directory)

To delete everything inside the current directory while keeping the directory itself, use:

rm -rf *

This will remove all files and subfolders in the current directory.


Safety Tips When Using rm

  • Double-check file paths before running rm -rf, as there is no undo option.
  • Use ls before rm to verify the files/folders you are about to delete:shCopyEditls myFile*
  • If unsure, use the interactive mode (-i flag) to confirm each file before deletion:shCopyEditrm -ri foldername/

Conclusion

The rm command is a powerful tool for managing files and folders via SSH. Whether deleting specific files, entire directories, or using wildcards for batch deletion, understanding these commands will help you manage your server efficiently. Always use caution when using rm -rf, as accidental deletions can be irreversible.

Happy coding! 🚀

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *