LoginSignup
7
5

[macOS]コマンドでファイルを安全に削除する方法

Last updated at Posted at 2023-04-04

概要

rmコマンドだとファイルがゴミ箱に移動されずそのまま削除されてしまうので、操作を間違えると大惨事になる場合があります。ということで今回はコマンドでファイルを安全に削除する方法&ツール2選を紹介していきます。

  • 環境
    • (m2 pro)macOS Ventura 13

関数&aliasを作る

ファイルをゴミ箱に入れたい場合、以下のコマンドが使えます。

% mv <target file> ~/.Trash

このコマンドのaliasを作って、~/.zshrc(zshの場合)に追記すればOK。
コマンドに引数としてファイルパスを渡す必要があるので、関数を使います。

.zshrc
function moveToTrash() { mv $1 ~/.Trash }
alias rm='moveToTrash'

動作確認します。

% source ~/.zshrc
% cd /tmp
% touch test
% rm test

ゴミ箱に移動されましたね。
image.png

※上記のようなmoveToTrash関数の書き方では、通常rmコマンドのオプションやコミ箱から元のパスへのファイルの復元できないので、ご注意ください。

trashというツールを使う

trashというツールがあるので、こちらの方がもっと便利かもしれません。
まずbrewでインストールします。(Version 0.9.2)

% brew install trash
% trash
usage: trash [-vlesyF] <file> [<file> ...]

  Move files/folders to the trash.

  Options to use with <file>:

  -v  Be verbose (show files as they are trashed, or if
      used with the -l option, show additional information
      about the trash contents)
  -F  Ask Finder to move the files to the trash, instead of
      using the system API.

  Stand-alone options (to use without <file>):

  -l  List items currently in the trash (add the -v option
      to see additional information)
  -e  Empty the trash (asks for confirmation)
  -s  Securely empty the trash (asks for confirmation)
  -y  Skips the confirmation prompt for -e and -s.
      CAUTION: Deletes permanently instantly.

  Options supported by `rm` are silently accepted.

aliasを作っておきます。

.zshrc
alias rm='trash'

動作確認します。

% source ~/.zshrc
% cd /tmp
% touch test
% rm test

ゴミ箱に移動されましたね。
image.png

他にも色々なオプションがあるので、helpメッセージを読んでみてください。

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5