Delete file mac os terminal

How to Delete a File in Terminal on Your Mac

Use the command line to permanently delete files from a Mac

What to Know

  • In a Finder window, go to Applications >Utilities, type rm, space, drag the file to the Terminal window, and press Enter.
  • You can also press Command+Space to open Spotlight, type terminal, and press Enter to access the Terminal window.

In this guide, we show you how to delete a file in Terminal on Mac computers with macOS and OS X Lion (10.7) and later.

What Is Terminal?

Terminal is an app that comes with every Mac. It’s a way to use the command line on the Mac. It allows you to modify settings, files, and other features beyond what is available in the graphical user interface (GUI). The command line offers you total command of your Mac, from the inside out.

Why should you use Terminal? Here are a few of the key benefits of using Terminal for Mac:

  • It rings true to Unix: Mac users coming over from Unix will find Terminal easier to use due to its similarity.
  • It allows you to unlock all preference settings: Everything you can customize can be unlocked using Terminal, even things you can’t access through the GUI.
  • It cuts down on clicks: Want to move all your files from one folder to another? A few seconds of typing in Terminal is all you need, versus the time and clicks it takes to transfer files manually.
  • It helps you remove files with ease: If you want to remove a file from your Mac forever, you can skip the Trash and use Terminal. It’s quick, only taking a few seconds.

The Terminal is a dangerous place if you’re inexperienced in the command line. Before you enter Terminal, familiarize yourself with the basic commands. One wrong command can damage your system.

How to Delete a File in Terminal on Your Mac

Whether you’re dealing with a problem file that refuses to leave your Mac or you want to delete multiple files quickly, Terminal makes it quick and easy. Here’s how:

Navigate to Terminal on your Mac by opening a Finder window and selecting Applications > Utilities.

You can also press Command+Space to open Spotlight. Then, type terminal and press the Enter key.

In the Terminal window, type rm and a space. Next, drag the file you want to delete into the Terminal window.

Press Enter, and the file is gone forever.

Want to go faster? Remove the file by entering the path to the file into Terminal, without the drag and drop.

There you have it. Harness your new power to delete files easily, but remember to use it with care.

Источник

Как удалить файл в терминале на вашем Mac

Каждый хочет сэкономить время и силы при выполнении задач на своем Mac. Благодаря терминалу командной строки пользователи Mac могут легко выполнить утомительные задачи всего за несколько секунд, включая удаление файлов. Продолжайте читать, чтобы узнать, как удалить файл в терминале.

Читайте также:  Mac os catalina сброс пароля администратора

Инструкции в этой статье относятся к пользователям Mac, использующим macOS и OS X Lion и новее.

Что такое терминал?

Терминал это приложение, которое поставляется с каждым Mac. Это способ использовать командную строку на Mac и позволяет пользователям изменять настройки, файлы и т. Д. Помимо того, что доступно в графическом интерфейсе пользователя (GUI). Командная строка предлагает пользователям полное управление своим Mac, изнутри.

Почему вы должны использовать терминал? Вот только некоторые из ключевых преимуществ использования Terminal for Mac:

  • Это звучит правдоподобно для Unix : пользователи Mac, пришедшие из Unix , обнаружат, что Terminal намного проще в использовании, поскольку он знаком с такой работой.
  • Он позволяет разблокировать все настройки параметров : все, что вы можете настроить, можно разблокировать с помощью терминала, даже вещи, к которым вы не можете получить доступ с помощью графического интерфейса пользователя .
  • Он сокращает количество нажатий : хотите переместить все ваши файлы из одной папки в другую? Все, что вам нужно — это набрать несколько секунд в терминале, в отличие от времени и кликов, которые требуются для их переноса вручную.
  • Это поможет вам удалить файлы с легкостью — навсегда : если вы хотите навсегда удалить файл с вашего Mac, вы можете пропустить корзину и использовать терминал. Это быстро, займет всего несколько секунд.

Важно понимать, что Терминал является опасным местом для тех, кто неопытен в командной строке. Прежде чем войти в Терминал, обязательно ознакомьтесь с основными командами. Одна неправильная команда может повредить вашу систему.

Как удалить файл в терминале на вашем Mac

Независимо от того, имеете ли вы дело с проблемным файлом, который отказывается покидать ваш Mac, или вы просто хотите быстро удалить несколько файлов, Terminal делает это быстро и легко.

Найдите терминал на своем Mac, открыв приложения и выбрав Утилиты . Вы также можете найти Терминал в разделе Другое.

Вы также можете нажать Ctrl + Space, чтобы открыть Spotlight. Затем введите Терминал.

В окне терминала введите rm и пробел. Затем вы можете просто перетащить файл, который вы хотите удалить, в окно терминала.

Нажмите Enter, и файл исчезнет навсегда.

Источник

How to remove files and directories quickly via terminal (bash shell) [closed]

Want to improve this question? Update the question so it’s on-topic for Stack Overflow.

Closed 6 years ago .

From terminal window:

When I use the rm command it can only remove files.
When I use the rmdir command it only removes empty folders.

If I have a directory nested with files and folders within folders with files and so on, is there any way to delete all the files and folders without all the strenuous command typing?

If it makes a difference, I am using the mac bash shell from terminal, not Microsoft DOS or linux.

4 Answers 4

-r «recursive» -f «force» (suppress confirmation messages)

Would remove everything (folders & files) in the current directory.

But be careful! Only execute this command if you are absolutely sure, that you are in the right directory.

Yes, there is. The -r option tells rm to be recursive, and remove the entire file hierarchy rooted at its arguments; in other words, if given a directory, it will remove all of its contents and then perform what is effectively an rmdir .

The other two options you should know are -i and -f . -i stands for interactive; it makes rm prompt you before deleting each and every file. -f stands for force; it goes ahead and deletes everything without asking. -i is safer, but -f is faster; only use it if you’re absolutely sure you’re deleting the right thing. You can specify these with -r or not; it’s an independent setting.

And as usual, you can combine switches: rm -r -i is just rm -ri , and rm -r -f is rm -rf .

Читайте также:  The command failed windows report

Also note that what you’re learning applies to bash on every Unix OS: OS X, Linux, FreeBSD, etc. In fact, rm ‘s syntax is the same in pretty much every shell on every Unix OS. OS X, under the hood, is really a BSD Unix system.

Источник

Remove directory in Terminal & other ways to delete files and folders on Mac

Before we start

Having spent some years coding applications for macOS we’ve created a tool that everybody can use. The all-round problem fixer for Mac.

So here’s a tip for you: Download CleanMyMac to quickly solve some of the issues mentioned in this article. But to help you do it all by yourself, we’ve gathered our best ideas and solutions below.

Features described in this article refer to the MacPaw site version of CleanMyMac X.

One of the most basic computer functions — deleting files and folders — is also one of the most essential. If you never get rid of anything, soon enough all those extra gigabytes will take a toll on your Mac’s processing power, RAM, and hard drive, not to mention your digital life will resemble a dreadful episode of Hoarders.

So deleting files is good and healthy. But how do you do that? Most people right-click on what they need gone and choose Move to Trash from the menu or use the File option in the menu bar. Others employ the ⌘ + Delete shortcut, which works across the system (even within dialog windows). Experts, however, often find themselves defaulting to the command line delete directory feature. Let’s see how and why you should learn it too.

How to remove directory with Terminal

Since macOS is a Unix-based system, nearly all system tasks you do every day with the help of its graphic interface can also be performed via the command line tool called Terminal.

Why delete file command line feature is important

With regards to delete file or delete folder command line functionality, Terminal lets you:

  • Effortlessly erase one or multiple files, folders, and apps, bypassing any error messages you can get when you go the traditional route.
  • Remove files from Trash, including ones you can’t delete by simply emptying the trash.
  • Get rid of files that are invisible to you within Finder (usually system or root files, for example, .htaccess).
  • Delete files and folders in cases when Finder is unresponsive.

Note: The Mac command line delete file feature is final and irreversible. While it lets you avoid any error messages, it also removes the files completely, without any possibility of retrieving them later on.

Tip: Delete unneeded system files on Mac

Some files are hard to delete in a normal way because they sit deeply in system folders. These are such files as logs, broken downloads, caches, remains of old apps, etc. Still, deleting them could give your Mac an extra boost — that’s because they are outdated and clutter your macOS.

To dig these files out, try a free version of CleanMyMac X. Among other things, this app has an impressive System Junk detector. When you download CleanMyMac X (this free version is notarized by Apple), you need to click on System Junk.

Just take a look at the sheer amount of files it unearthed. To delete them, click on Clean.

How to use delete file command line feature

Removing files from your Mac forever using Terminal is deceptively simple: just use the rm command followed by the name of the file. Here’s how it works in practice:

  1. Launch Terminal from your Utilities folder in Applications.
  2. Check which directory you’re in by typing ls -la
  3. Then navigate down a directory with cd [directoryname] or up a directory with cd ../
  4. When you’re in the same directory as the file you want to delete, type rm [filename.extension]
  5. If you want to delete multiple files at once, list them all, but make sure there’s a space between each one.
  6. Press Enter to execute the command.
Читайте также:  Создание ролей windows server 2016

Now all the files you specified after rm are gone for good. Navigate directories in your Mac and repeat the process as many times as you want.

Surprised there was no confirmation before your files were deleted? Luckily there’s a way to add one as a safeguard for not deleting the wrong file by accident. Just use -i after the rm but before the first filename, like this: rm -i [filename.extension]. Terminal will then ask you whether you’re sure you want to delete the file. Reply y or yes followed by Enter and the file will be gone. This also works for multiple files, but you’ll have to confirm the removal of each one separately.

How to make command line delete directory

Surprisingly, you can’t delete a folder using the rm command because it has its own: rmdir.

Otherwise, rmdir works exactly the same as rm:

  1. Navigate to the appropriate directory using Terminal.
  2. Type rmdir [directoryname]
  3. Hit Enter.

Sadly, you can’t use the -i hack when you’re deleting folders, so be extra careful!

Another thing to keep in mind is that rmdir only deletes the directory, but can’t delete any files or folders located within that directory.

To delete a folder with everything in it, you need to use rm -r followed by the folder’s name. Using -i to create a warning here is possible and done like this: rm -ir [foldername].

When it’s too difficult to find a folder or file via Terminal, but you can detect them in Finder, simply drag and drop the file onto the Terminal window to generate its path.

Delete large and old folders using CleanMyMac X

As it happens with folders, they are easy to mess up and lose track of. That’s why many apps provide an alternative interface for searching and deleting files which is more flexible than the Finder. For example, using CleanMyMac X (the app we’ve mentioned above) you can find massive folders that might have been evading you. You also can filter them by file type and other criteria.

The latest released version of this tool looks like this:

This app by developer MacPaw is available for a free download here. Using this app, files are removed for good, and as far as we know, it’s irreversible.

Other ways to delete files and folders on Mac

The shortcut combination

We are sure you know how to drag your files to the Trash. But here is an alternative way that deletes files at once, bypassing the Trash. There’s one less step involved (you don’t have to empty the bin). And you cannot reverse this action.

Select a file, and press [Option + + Delete]

Delete hidden folders on Mac

Some folders on your Mac are made invisible to protect them from accidental deletion. They are system and support files you would ignore most of the time. But what if a folder seems empty but still takes up space? You can apply another shortcut combination to highlight these unseen objects. Then, you can delete them at your own risk.

To highlight hidden folders: [Press Shift + + . dot key]
This best works if you open some system folder, like Library

Again, delete these folders only if you are sure what they are.

That was how to remove files and folders on your Mac, shown in multiple ways. Want to know more? Explore our blog for a whole universe of Mac tips!

Источник

Оцените статью