Я хотел бы знать, есть ли команда, которую я могу выполнить в терминале, чтобы я классически не удалял (rm
) файл, а вместо этого перемещал его в мусорную корзину (т. Е. Поведение Nautilus Move to Trash). ]
В случае, если есть такая команда, мне также было бы интересно узнать, что это такое.
Вы можете использовать gvfs-trash
команда из пакета gvfs-bin
, который по умолчанию установлен в Ubuntu.
Переместить файл в корзину:
gvfs-trash filename
Посмотреть содержимое корзины:
gvfs-ls trash://
Очистить корзину:
gvfs-trash --empty
Установите trash-cli - sudo apt-получите установку trash-cli
Положите файлы в мусорную корзину с: мусором file1 file2
Перечислить файлы в мусоре: мусорный список
пустой мусор: мусор -пустой
По состоянию на 2017 год gvfs-trash
, по-видимому, устарел.
$ touch test
$ gvfs-trash test
This tool has been deprecated, use 'gio trash' instead.
See 'gio help trash' for more info.
Вы должны использовать gio
, в частности
gio trash
- рекомендуемый способ.
Мне больше нравятся более простые способы. Я создал папку .Tr
в своем домашнем каталоге, набрав:
mkdir ~/.Tr
и вместо того, чтобы использовать rm
для удаления файлов, я перемещаю эти файлы в каталог ~/.Tr
, набрав:
mv fileName ~/.Tr
Это эффективный и простой способ сохранить доступ к файлам, которые, по вашему мнению, вам не нужны. Это имеет дополнительное преимущество (в моем случае) - не связываться с системными папками, так как уровень моих знаний Ubuntu довольно низок, и я беспокоюсь о том, что я могу испортить, когда связываюсь с системными вещами. Если вы также низкий уровень, пожалуйста, обратите внимание, что "." в названии каталога делает его скрытым.
В предыдущем ответе упоминается команда gio trash, и это нормально насколько это возможно. Однако на серверных машинах нет эквивалента каталога корзины. Я написал сценарий Bash, который выполняет эту работу; на настольных компьютерах (Ubuntu) он использует gio trash. (Я добавил псевдоним tt = 'move-to-trash '
в мой файл определений псевдонимов; tt
- мнемоника для «в корзину».) Скрипт протестирован на работу; Сам пользуюсь постоянно. Скрипт обновлен 10 августа 2020 г.
#!/bin/bash
#
# move-to-trash
#
# Teemu Leisti 2020-08-10
#
# This script moves the files given as arguments to the trash directory, if they
# are not already there. It works both on (Gnome) desktop and server hosts. (The
# gio command only exists for Gnome.)
#
# The script is intended as a command-line equivalent of deleting a file from a
# graphical file manager, which, in the usual case, moves the deleted file(s) to
# a built-in trash directory. On server hosts, the analogy is not perfect, as
# the script does not offer the functionality of restoring a trashed file to its
# original location, nor that of emptying the trash directory; rather, it offers
# an alternative to the 'rm' command, giving the user the peace of mind that
# they can still undo an unintended deletion before emptying the trash
# directory.
#
# To determine whether it's running on a desktop host, the script tests for the
# existence of the gio command and of directory ~/.local/share/Trash. In case
# both exist, the script relies on the 'gio trash' command. Otherwise, it treats
# the host as a server.
#
# There is no built-in trash directory on server hosts, so the script creates
# directory ~/.Trash/, unless it already exists.
#
# The script appends a millisecond-resolution time stamp to all the files it
# moves to the trash directory, both to inform the user of the time of the
# deletion, and to avoid overwrites when moving a file to trash.
#
# The script will not choke on a nonexistent file. It outputs the final
# disposition of each argument: does not exist, was already in trash, or was
# moved to trash.
gio_command_exists=0
command -v gio > /dev/null 2>&1
if (( $? == 0 )) ; then
gio_command_exists=1
fi
# Exit on using an uninitialized variable, and on a command returning an error.
# (The latter setting necessitates appending " || true" to those arithmetic
# calculations and other commands that can return 0, lest the shell interpret
# the result as signalling an error.)
set -eu
is_desktop=0
if [[ -d ~/.local/share/Trash ]] && (( gio_command_exists == 1 )) ; then
is_desktop=1
trash_dir_abspath=$(realpath ~/.local/share/Trash)
else
trash_dir_abspath=$(realpath ~/.Trash)
if [[ -e $trash_dir_abspath ]] ; then
if [[ ! -d $trash_dir_abspath ]] ; then
echo "The file $trash_dir_abspath exists, but is not a directory. Exiting."
exit 1
fi
else
mkdir $trash_dir_abspath
echo "Created directory $trash_dir_abspath"
fi
fi
for file in "$@" ; do
file_abspath=$(realpath -- "$file")
file_basename=$(basename -- "$file_abspath")
if [[ ! -e $file_abspath ]] ; then
echo "does not exist: $file_abspath"
elif [[ "$file_abspath" == "$trash_dir_abspath"* ]] ; then
echo "already in trash: $file_abspath"
else
if (( is_desktop == 1 )) ; then
gio trash "$file_abspath" || true
else
# The name of the moved file shall be the original name plus a
# millisecond-resolution timestamp.
beginning="$trash_dir_abspath/$file_basename"_DELETED_ON_
move_to_abspath="$beginning$(date '+%Y-%m-%d_AT_%H-%M-%S.%3N')"
while [[ -e "$move_to_abspath" ]] ; do
# Generate a new name with a new timestamp, as the previously
# generated one denoted an existing file.
move_to_abspath="$beginning$(date '+%Y-%m-%d_AT_%H-%M-%S.%3N')"
done
# We're now almost certain that the file denoted by name
# $move_to_abspath does not exist. For that to be the case, an
# extremely unlikely race condition would have had to take place:
# some other process would have had to create a file with the name
# $move_to_abspath after the execution of the existence test above.
# However, to make absolute sure that moving the file to the trash
# directory will always be successful, we shall give the '-f'
# (force) flag to the 'mv' command.
/bin/mv -f "$file_abspath" "$move_to_abspath"
fi
echo "moved to trash: $file_abspath"
fi
done
Здесь - это версия с открытым исходным кодом на основе nodejs (если вы хотите знать, что происходит под капотом, или вам это нужно в проекте), которая также имеет поддержку командной строки (если вы счастлив, если он просто работает).
> trash pictures/beach.jpg
Обновление @Radu Rădeanu
ответ. Поскольку Ubuntu советует мне использовать вместо этого gio
...
Итак, чтобы выбросить some_file
(или папку) в корзину, используйте
gio trash some_file
Чтобы перейти в корзину, используйте
gio list trash://
Чтобы очистить trash
gio trash --empty
В KDE 4.14.8 я использовал следующую команду для перемещения файлов в корзину (как если бы они были удалены в Dolphin):
kioclient move path_to_file_or_directory_to_be_removed trash:/
Приложение: Я нашел информацию о команде с
ktrash --help
...
Note: to move files to the trash, do not use ktrash, but "kioclient move 'url' trash:/"
EDIT : Для KDE 5.18.5 это команда kioclient5
, синтаксис идентичен.
Если вы используете zsh, настройте setopt rmstarwith
для вашего терминала вместо. См. Ниже.
$ setopt rmstarwith
$ rm -rf *
//zsh: sure you want to delete the only file in /Users/Dylan/tmp [yn]?
$ y
Вам будет предложено подтвердить ваше действие при удалении файлов командой rm
.
Вы также можете ввести n
, чтобы отменить операцию.