`rm`을 휴지통으로 이동하게 합니다.

`rm`을 휴지통으로 이동하게 합니다.

파일을 삭제하는 대신 특별한 "휴지통" 위치로 이동시키는 Linux 스크립트/응용 프로그램이 있습니까? 나는 이것을 대체하고 싶습니다 rm(아마도 후자에 별칭을 붙일 수도 있습니다. 이에 대한 장단점이 있습니다).

"휴지통"이란 특수 폴더를 의미합니다. 단일이 mv "$@" ~/.trash첫 번째 단계이지만 이상적으로는 이전에 휴지통에 버린 파일을 덮어쓰지 않고 동일한 이름의 여러 파일을 휴지통에 처리해야 하며 다음을 수행할 수 있어야 합니다.복원하다간단한 명령(일종의 "실행 취소")을 사용하여 파일을 원래 위치로 복사합니다. 또한 재부팅 시 휴지통이 자동으로 비워지면 좋을 것입니다(또는 끝없는 성장을 방지하기 위한 유사한 메커니즘).

이에 대한 부분적인 해결책이 존재하지만 특히 "복원" 작업은 쉽지 않습니다. 그래픽 쉘의 휴지통 시스템에 의존하지 않는 기존 솔루션이 있습니까?

(여담으로, 빈번한 백업과 VCS를 사용하는 것보다 이 접근 방식이 정당한지에 대한 끊임없는 논의가 있었습니다. 이러한 논의에는 일리가 있지만 제 요청에는 여전히 틈새 시장이 있다고 생각합니다.)

답변1

이있다휴지통 사양(초안)freedesktop.org에서. 이는 일반적으로 데스크탑 환경에서 구현되는 것 같습니다.

명령줄 구현은 다음과 같습니다.쓰레기-cli. 자세히 살펴보지 않고도 원하는 기능을 제공하는 것 같습니다. 그렇지 않다면 이것이 어느 정도 부분적인 해결책인지 알려주십시오.

어떤 프로그램을 대체/별칭으로 사용하는 한 rm, 그렇게 하지 않는 데는 충분한 이유가 있습니다. 나에게 가장 중요한 것은 다음과 같습니다.

  • rm프로그램은 의 모든 옵션을 이해/처리하고 그에 따라 행동해야 합니다 .
  • "새 rm"의 의미에 익숙해지고 다른 사람의 시스템에서 작업할 때 치명적인 결과를 초래하는 명령을 수행할 위험이 있습니다.

답변2

이전 답변에는 명령 trash-clirmtrash. Ubuntu 18.04에서는 기본적으로 이들 중 어느 것도 발견되지 않지만 다음 명령은gio이다. 명령 gio help trash출력:

Usage:
  gio trash [OPTION…] [LOCATION...]

Move files or directories to the trash.

Options:
  -f, --force     Ignore nonexistent files, never prompt
  --empty         Empty the trash

나는 다음을 사용하여 테스트했습니다.gio trash FILENAME명령줄에서 실행하면 파일 브라우저에서 파일을 선택하고 DEL 버튼을 클릭한 것처럼 작동합니다. 파일은 데스크탑의 휴지통 폴더로 이동됩니다. (옵션을 사용하지 않았음에도 명령에서 확인 메시지가 표시되지 않습니다 -f.)

rm이 방법으로 파일을 삭제하는 것은 되돌릴 수 있지만, 안전 을 위해 재정의하고 각 삭제를 확인해야 하는 것보다 더 편리 rm -i하지만 실수로 삭제를 확인하면 운이 좋지 않습니다.

alias tt='gio trash'별칭 정의 파일에 추가했습니다 . tt"쓰레기"에 대한 니모닉입니다.

2018-06-27 편집에 추가됨:서버 시스템에는 휴지통 디렉토리에 해당하는 것이 없습니다. 나는 작업을 수행하는 다음 Bash 스크립트를 작성했습니다. 데스크톱 시스템에서는 를 사용하고 gio trash다른 시스템에서는 매개변수로 제공된 파일을 생성된 휴지통 디렉터리로 이동합니다. 스크립트는 작동 테스트를 거쳤습니다. 나는 항상 그것을 직접 사용합니다.2024-04-12에 스크립트가 업데이트되었습니다.

#!/bin/bash

# move_to_trash
#
# Teemu Leisti 2024-04-12
#
# USAGE:
#
#   Move the file(s) given as argument(s) to the trash directory, if they are
#   not already there.
#
# RATIONALE:
#
#   The script is intended as a command-line equivalent of deleting a file or
#   directory from a graphical file manager. On hosts that implement the
#   FreeDesktop.org specification on trash directories (hereon called "the trash
#   specification"; see
#   https://specifications.freedesktop.org/trash-spec/trashspec-latest.html),
#   that action moves the target file(s) to a built-in trash directory, and that
#   is exactly what this script does.
#
#   On other hosts, this script uses a custom trash directory (~/.Trash/). The
#   analogy of moving a file to trash is not perfect, as the script does not
#   offer the functionalities of restoring a trashed file to its original
#   location or emptying the trash directory. Rather, it offers an alternative
#   to the 'rm' command, thereby giving the user the peace of mind that they can
#   still undo an unintended deletion before emptying the custom trash
#   directory.
#
# IMPLEMENTATION:
#
#   To determine whether it's running on a host that implements the trash
#   specification, the script tests for the existence of (a) the gio command and
#   (b) either directory $XDG_DATA_HOME/Trash/, or, if that environment variable
#   hasn't bee set, of directory ~/.local/share/Trash/. If the test yields true,
#   the script relies on calling 'gio trash'.
#
#   On other hosts:
#     - There is no built-in trash directory, so the script creates a custom
#       directory ~/.Trash/, unless it already exists. (The script aborts if
#       there is an existing non-directory ~/.Trash.)
#     - The script appends a millisecond-resolution timestamp to all the files
#       it moves to the custom trash directory, to both inform the user of the
#       time of the trashing, and to avoid overwrites.
#     - The user will have to perform an undo by commanding 'mv' on a file or
#       directory moved to ~/.Trash/.
#     - The user will have to empty the custom trash directory by commanding:
#           rm -rf ~/.Trash/* ~/.Trash/.*
#
#   The script will not choke on a nonexistent file. It outputs the final
#   disposition of each filename argument: does not exist, was already in trash,
#   or was moved to trash.
#
# COPYRIGHT WAIVER:
#
#   The author dedicates this Bash script to the public domain by waiving all of
#   their rights to the work worldwide under copyright law, including all
#   related and neighboring rights, to the extent allowed by law. You can copy,
#   modify, distribute, and perform the script, even for commercial purposes,
#   all without asking for permission.

if [ -z "$XDG_DATA_HOME" ] ; then
    xdg_trash_directory=$(realpath ~/.local/share/Trash/)
else
    xdg_trash_directory=$(realpath $XDG_DATA_HOME/Trash/)
fi

gio_command_exists=0
if $(command -v gio > /dev/null 2>&1) ; then
    gio_command_exists=1
fi

host_implements_trash_specification=0
if [[ -d "${xdg_trash_directory}" ]] && (( gio_command_exists == 1 )) ; then
    # Executing on a host that implements the trash specification.
    host_implements_trash_specification=1
    trash_directory="${xdg_trash_directory}"
else
    # Executing on other host, so attempt to use a custom trash directory.
    trash_directory=$(realpath ~/.Trash)
    if [[ -e "${trash_directory}" ]] ; then
        # It exists.
        if [[ ! -d "${trash_directory}" ]] ; then
            # But is not a directory, so abort.
            echo "Error: ${trash_directory} exists, but is not a directory."
            exit 1
        fi
    else
        # It does not exists, so create it.
        mkdir "${trash_directory}"
        echo "Created directory ${trash_directory}"
    fi
fi

# Deal with all filenames (a concept that covers names of both files and
# directories) given as arguments.
for file in "$@" ; do
    file_to_be_trashed=$(realpath -- "${file}")
    file_basename=$(basename -- "${file_to_be_trashed}")
    if [[ ! -e ${file_to_be_trashed} ]] ; then
        echo "does not exist:   ${file_to_be_trashed}"
    elif [[ "${file_to_be_trashed}" == "${trash_directory}"* ]] ; then
        echo "already in trash: ${file_to_be_trashed}"
    else
        # ${file_to_be_trashed} exists and is not yet in the trash directory,
        # so move it there.
        if (( host_implements_trash_specification == 1 )) ; then
            gio trash "${file_to_be_trashed}"
        else
            # Move the file to the custom trash directory, with a new name that
            # appends a millisecond-resolution timestamp to the original.
            head="${trash_directory}/${file_basename}"_TRASHED_ON_
            move_file_to="${head}$(date '+%Y-%m-%d_AT_%H-%M-%S.%3N')"
            while [[ -e "${move_file_to}" ]] ; do
                # Generate a new name with a new timestamp, as the previously
                # generated one denoted an existing file or directory. It's very
                # unlikely that this loop needs to be executed even once.
                move_file_to="${head}$(date '+%Y-%m-%d_AT_%H-%M-%S.%3N')"
            done
            # There is no file or directory named ${move_file_to}, so
            # we can use it as the move target.
            /bin/mv "${file_to_be_trashed}" "${move_file_to}"
        fi
        echo "moved to trash:   ${file_to_be_trashed}"
    fi
done

답변3

Trash-cliUbuntu에서는 apt-get을 사용하고 Fedora에서는 yum을 사용하여 설치할 수 있는 Linux 애플리케이션입니다. 명령을 사용하면 trash listOfFiles지정된 항목이 휴지통으로 이동됩니다.

답변4

함수 정의부터 시작하세요 move_to_trash.

move_to_trash () {
    mv "$@" ~/.trash
}

그런 다음 별칭을 지정 rm합니다.

alias rm='move_to_trash'

rm다음과 같이 백슬래시를 사용하여 이스케이프 처리하여 언제든지 old를 호출할 수 있습니다 \rm.

재부팅 시 휴지통 디렉터리를 비우는 방법을 모르지만(시스템에 따라 스크립트를 조사해야 할 수도 있음 ) 디렉터리를 주기적으로 비우는 작업을 rc*만드는 것도 가치가 있을 수 있습니다 .cron

관련 정보