How to Delete Files and Directories from MacOS Terminal
In this quick guide, we will see how to remove files and folders using the macOS Terminal application. Keep in mind that when you delete a file using the Terminal, there is no way to retrieve it. So be careful using it.
If you have been using Linux terminal, you will be familiar with the commands cause they are the same.
Deleting a file using Terminal
First, we will create a new folder from which we are going to delete files.
$ mkdir TestFolder
Navigate to the TestFolder using cd command (type the first couple of letters of the word TestFolder and press tab to auto-complete the directory name):
$ cd TestFolder/
Now let’s create a test file:
$ touch testfile.txt $ ls testfile.txt
To remove this file we will type the following:
$ rm testfile.txt
Remove a folder using Terminal
We will now create another folder within our TestFolder:
To remove it, we use rmdir command:
$ rmdir AnotherTestFolder/
Remember, this command will only work on an empty folder, it won’t delete a folder if it contains some files in it.
Force remove files and folders recursively
To remove a non-empty folder with files in it, we have to use the rm command with the following flags -Rf.
First, we will create the subfolder again and a couple of files within it:
$ mkdir AnotherTestFolder $ touch AnotherTestFolder\file1.txt $ touch AnotherTestFolder\file2.txt $ rm -Rf AnotherTestFilder\
The command for “rm” means to remove, the flag “R” is recursive which will allow you to delete the contents of a directory, and “f” means force, causing the Terminal to delete the file regardless of the error it may cause.
Removing all hidden files from a folder
To remove all hidden files in a folder (once that starts with a dot eg. .testfile) we will use:
$ rm -rf .*
We saw how the basic commands for file and folder removal work. There are a lot of advanced commands for other use cases, like deleting files of a certain type (like temp or backup files), finding and deleting files with the desired filename pattern, etc.
* You will receive the latest news and updates directly to your inbox !