Команда перемістити файл у кошик через термінал


117

Мені хотілося б знати, чи є команда, яку я можу видати в терміналі, тому я не класично видаляю ( rm) файл, а натомість переміщую його у кошик (тобто Nautilus Move to Trash).

Якщо є така команда, мені також було б цікаво знати, що це таке.


2
Подивіться на цю відповідь .
Персик

2
Також хороший ресурс тут: webupd8.org/2010/02/make-rm-move-files-to-trash-instead-of.html
Rinzwind

Відповіді:


105

Ви можете використовувати gvfs-trashкоманду з пакета gvfs-bin, встановленого за замовчуванням в Ubuntu.

Перемістити файл у кошик:

gvfs-trash filename

Переглянути вміст кошика:

gvfs-ls trash://

Очистіть кошик:

gvfs-trash --empty

Також відвідайте моє gvfs-запитання .
Пандія

Це найпростіша відповідь для мене, яка працює. Дякую.
Теоді К. Сегуїн

10
Згідно з man gvfs-trashцим застаріло на користь gio trash, див man gio.
pbhj

67

Встановити кошик для сміттяВстановіть кошик для сміття -sudo apt-get install trash-cli

Помістіть файли у кошик за допомогою: trash file1 file2

Список файлів у кошику: trash-list

Порожній кошик із: trash-empty


1
Цей (пов'язаний з Ubuntu) інструмент вказує на кошик . Досить цікаво, не впевнений, наскільки широко прийнятий, хоча ...
Френк Нокк

Після встановлення я запускаю команду і отримую помилку: File "/usr/bin/trash-list", line 4, in <module> ImportError: No module named 'trashcli'
Даніель,

25

Станом на 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

є рекомендованим способом.


2
Чи можете ви пов’язати джерело, gvfs-trashяке застаріло, і що gioтаке?
Мелебій

1
На жаль, я не можу надати посилання, але це те, що я намагаюся використати gvfs-trash на Kubuntu 17.10: pastebin.com/HA4a1pbs
Eugen Tverdokhleb

1
Ви можете вставити приклад у свою відповідь, мені це буде достатньо разом із номером версії системи. Я використовую 16,04 LTS, і gvfs-trashце єдиний варіант.
Мелебій

Цей інструмент має купу інших приємних функцій. Мені подобається infoкоманда; здається корисним.
Раффі Хатчадуріан

4

Оновлення @Radu Rădeanuвідповіді. Оскільки Ubuntu каже мені використовувати gioзамість цього ...

Отже, для сміття some_file(або папки) використовуйте

gio trash some_file

Щоб піти на дайвінг використовувати дайвінг

gio list trash://

Щоб випорожнити сміття

gio trash --empty

3

Мені подобаються найкращі способи низьких технологій. Я створив папку .Trу своєму домашньому каталозі, ввівши:

mkdir ~/.Tr

і замість використання rmдля видалення файлів я переміщу ці файли до ~/.Trкаталогу, ввівши:

mv fileName ~/.Tr

Це ефективний і простий спосіб зберегти доступ до файлів, які, на вашу думку, не хочете, з додатковою перевагою, в моєму випадку не псуюся з папками системи, оскільки мій рівень знань Ubuntu досить низький, і я хвилююся, що я можу бути викручування, коли я псуюся з системними речами. Якщо ви також низького рівня, врахуйте, що "." в імені каталогу це робить прихований каталог.


3

У попередній відповіді згадується команда gio trash, що добре, наскільки це йде. Однак на серверних машинах немає еквівалента каталогу сміття. Я написав сценарій Баша, який виконує цю роботу; на (Ubuntu) настільних машинах, які він використовує gio trash. (Я додав alias tt='move-to-trash'у свій файл визначення псевдонімів; ttце мнемонічне значення для "сміття".)

#!/bin/bash
# move-to-trash

# Teemu Leisti 2018-07-08

# This script moves the files given as arguments to the trash directory, if they
# are not already there. It works both on (Ubuntu) desktop and server hosts.
#
# 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 functionalities of restoring a trashed file to
# its original location nor of emptying the trash directory; rather, it is an
# alternative to the 'rm' command that offers the user the peace of mind that
# they can still undo an unintended deletion before they empty the trash
# directory.
#
# To determine whether it's running on a desktop host, the script tests for the
# existence of directory ~/.local/share/Trash. In case it is, the script relies
# on the 'gio trash' command.
#
# When not running on a desktop host, there is no built-in trash directory, so
# the first invocation of the script creates one: ~/.Trash/. It will not
# overwrite an existing file in that directory; instead, in case a file given as
# an argument already exists in the custom trash directory, the script first
# appends a timestamp to the filename, with millisecond resolution, such that no
# existing file will be overwritten.
#
# 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 the trash.


# Exit on using an uninitialized variable, and on a command returning an error.
# (The latter setting necessitates appending " || true" to those arithmetic
# calculations that can result in a value of 0, lest bash interpret the result
# as signalling an error.)
set -eu

is_desktop=0

if [[ -d ~/.local/share/Trash ]] ; 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
            move_to_abspath="$trash_dir_abspath/$file_basename"
            while [[ -e "$move_to_abspath" ]] ; do
                move_to_abspath="$trash_dir_abspath/$file_basename-"$(date '+%Y-%m-%d-at-%H:%M:%S.%3N')
            done
            # While we're reasonably sure that the file at $move_to_abspath does not exist, we shall
            # use the '-f' (force) flag in the 'mv' command anyway, to be sure that moving the file
            # to the trash directory is successful even in the extremely unlikely case that due to a
            # run condition, some other thread has created the file $move_to_abspath after the
            # execution of the while test above.
            /bin/mv -f "$file_abspath" "$move_to_abspath"
        fi
        echo "moved to trash:   $file_abspath"
    fi
done


0

У 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:/"
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.