Я использовал бы любой дистрибутив, Вы являетесь самыми знакомыми с администрированием (предпочтительно, что находится в хост-системе для создания инструментов легкими). Вам не нужен абсолютно отдельный дистрибутив, чтобы сделать это, все, в чем Вы нуждаетесь, набор пакета и сценарий установки для установки тока / предпочтенный дистрибутив к системе конечного файла (в петлевом файле для создания изображения диска). Это получит Вас точно набор инструментов, в которых Вы нуждаетесь и не больше с небольшой суетой и более низкой кривой обучения, чем автоматизация установки некоторого другого дистрибутива.
Если Вы заявляете предпочтительный дистрибутив и задаете конкретный вопрос, я уверен, что кто-то здесь может быть полезным с деталями.
Существует спецификация (проект) для Мусора на freedesktop.org. Это, по-видимому, что обычно реализуется настольными средами.
Реализация командной строки была бы мусором-cli. Не более внимательно рассмотрев, это, кажется, обеспечивает funtionality, который Вы хотите. В противном случае скажите нам в том, как далеко это - только частичное решение.
До использования любой программы как замена/псевдоним для rm
затронут, существуют серьезные основания не сделать это. Самый важный для меня:
rm
опции и действие соответственноВот быстрая и грязная система мусора, которая справляется со столкновениями имени и даже позволяет несколько удаленных файлов на том же пути, пока Вы не удаляете больше чем один файл в секунду.
Предупреждение: Я ввел этот код непосредственно в мой браузер. Это, вероятно, повреждается. Не используйте его на производственных данных.
trash_root=~/.trash
mkdir "$trash_root"
newline='
'
trash () (
time=$(date +%Y%m%d%H%M%S)
for path; do
case $path in /*) :;; *) path=$PWD/$path;; esac
mkdir "$trash_root${path%/*}"
case ${path##*/} in
?*.*) ext="${path##*.}"; ext="${ext##*$newline}";;
*) ext="";;
esac
metadata="Data: $hash.$ext
Date: $time
Path: $path
"
hash=$(printf %s "$metadata" | sha1sum)
printf %s "$metadata" "$trash_root/$hash-$time-metadata"
mv "$path" "$trash_root/$hash.$ext"
done
)
untrash () (
IFS='
'
root=$PWD
cd "$trash_root" || return 2
err=0
for path; do
if [ -e "$path" ]; then
echo 1>&2 "Not even attempting to untrash $path over an existing file"
if [ $err -gt 2 ]; then err=2; fi
continue
fi
case $path in /*) :;; *) path=$root/$path;; esac
if metadata=$(grep -l -F -x "Path: $path" *-metadata |
sort -t - -k 2 | tail -n 1); then
mv "${metadata%%-*}".* "$path"
else
echo 1>&2 "$path: no such deleted file"
if [ $err -gt 1 ]; then err=1; fi
fi
done
return $err
)
Известные проблемы:
trash
должен справиться с новыми строками в именах файлов, но untrash
не делает, потому что это полагается grep
и новых строк не оставляют в файле метаданных.Запустите путем определения a move_to_trash
функция:
move_to_trash () {
mv "$@" ~/.trash
}
Затем псевдоним rm
к этому:
alias rm='move_to_trash'
Можно всегда называть старым rm
путем выхода из него с обратной косой чертой, как это: \rm
.
Я не знаю, как сделать каталог мусора пустым на перезагрузке (в зависимости от Вашей системы, Вам, вероятно, придется изучить rc*
сценарии), но могло также стоить создать a cron
задача, которая периодически освобождает каталог.
rm
и там пойдите свои файлы. del
мог бы быть лучший выбор.
– glenn jackman
11.07.2012, 03:51
Есть небольшая утилита под названием rmtrash , которая делает это.
Похоже, он не отвечает на такие параметры, как -r
или -f
(по сути, это просто перемещение файла / каталога в каталог ~ / .Trash) , но он не переопределит файлы с тем же именем (он добавляет «Копировать» к файлам / каталогам с одинаковыми именами).
Для установки с пивом
brew install rmtrash
alias rm='rmtrash' >> ~/.bashrc
Вы можете использовать PartClone
, он понимает, что внутренние клоны файловой системы, так что он резервное копирование только данных и метаданных при пропуске пустого пространства.
TRASH-CLI - это приложение Linux, которое может быть установлено с использованием APT-Get в Ubuntu или yum в Fedora. Используя команду Trash ListOffiles
будет перемещать указанный в ваш мусорное ведро.
Вы можете использовать мой del:
http://fex.belwue.de/fstools/del.html
del перемещает файлы в подкаталог .del / (и обратно)
usage: del [-v] [-u] file(s) del [-v] -p [-r] [-d days] [directory] del [-v] -l options: -v verbose mode -u undelete file(s) -p purge deleted files [older than -d days] -r recursive (all subdirectories) -l list deleted files examples: del *.tmp # delete all *.tmp files del -u project.pl # undelete project.pl del -vprd 2 # verbose purge deleted files older than 2 days
Las respuestas anteriores mencionan los comandos trash-cli
y rmtrash
. Ninguno de ellos se encuentra de forma predeterminada en Ubuntu 18.04, pero el comandogio
sí. Comando gio help trash
salidas:
Usage:
gio trash [OPTION…] [LOCATION...]
Move files or directories to the trash.
Options:
-f, --force Ignore nonexistent files, never prompt
--empty Empty the trash
Probé usandogio trash FILENAME
en la línea de comando, y funciona como si hubiera seleccionado el archivo en el explorador de archivos y hecho clic en el botón DEL :, el archivo se mueve a la carpeta Papelera del escritorio. (El comando no solicita confirmación a pesar de que no usé la opción -f
.)
La eliminación de archivos de esta manera es reversible, aunque es más conveniente que redefinir rm
para que sea rm -i
por seguridad y tener que confirmar cada eliminación, lo que aún lo deja sin suerte si confirma accidentalmente una eliminación que no debería tener.
Agregué alias tt='gio trash'
a mi archivo de definiciones de alias; tt
es un mnemotécnico para To Trash.
Agregado en la edición de 2018 -06 -27:En las máquinas de servidor, no hay equivalente a un directorio de basura. He escrito el siguiente script Bash que hace el trabajo; en máquinas de escritorio, usa gio trash
, y en otras máquinas, mueve el archivo (s )dado como parámetro (s )a un directorio de basura que crea. Se prueba que el script funcione; Yo mismo lo uso todo el tiempo. Guión actualizado el 2021 -04 -27.
#!/bin/bash
#
# move_to_trash
#
# Teemu Leisti 2021-04-16
#
# 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
if command -v gio > /dev/null 2>&1 ; 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
В KDE 4.14.8 я использовал следующую команду для перемещения файлов в корзину (, как если бы они были удалены в Dolphin):
kioclient move path_to_file_or_directory_to_be_removed trash:/
Приложение I :Нашел про команду с
ktrash --help
...
Note: to move files to the trash, do not use ktrash, but "kioclient move 'url' trash:/"
Приложение II :функция (, затем источник ее в вашем.bashrc)
function Rm {
if [[ "$1" == '--help' ]] ; then
echo 'USAGE:'
echo 'Rm --help # - show help'
echo 'Rm file1 file2 file3...'
echo 'Works for files and directories'
return
fi
for i in "$@" ;
do
kioclient move $i trash:/ && echo "$i was trashed"
done
}
Я тестирую эту очень простую альтернативу, которая создает версию даты ~/.trash
для меня.
Я полагаю, что у него нет (действительно действительных )проблем, упомянутых в принятом ответе:
The program would need to understand/handle all of rm's options and act accordingly
Вы просто используете rm something
. Не нужно передавать какие-либо флаги. Если вы, скажем, запустите rm -rf
, он проигнорирует r
, так как mv
не поддерживает его, а f
не будет иметь большого значения, так как ~/.trash
имеет версию по дате..
It has the risk of getting used to the semantics of your "new rm" and performing commands with fatal consequences when working on other people's systems
Как я уже сказал, новая семантика в конечном итоге заставит меня бежать rm something
. Если я вернусь к использованию этого на других машинах, это будет работать только для файлов. Для папок это выдаст обычную ошибку типа «вам не хватает -r».
move_to_trash() {
local trash_dir
trash_dir="${HOME}/.trash"
if [ ! -d "${trash_dir}" ]; then
echo "Trash directory doesn't exist. Creating..."
mkdir "${trash_dir}"
echo "Created!"
fi
local new_dir_name
new_dir_name="${trash_dir}/$(date +%Y-%m-%d_%H-%M-%S)/"
mkdir "${new_dir_name}"
echo "Moving to: ${new_dir_name}"
mv "$@" ${new_dir_name}
echo 'Done!'
}
alias really-rm="/bin/rm"
alias rm="move_to_trash"
rm
таким образом, я не могу использовать его случайно (там тихо/bin/rm
в случае, если мне действительно нужен он). – Konrad Rudolph 05.09.2012, 11:16