Comando para mover un archivo a la Papelera a través de la Terminal


117

Me gustaría saber si hay un comando que pueda emitir en una terminal para que no elimine ( rm) el archivo de forma clásica , sino que lo mueva a la papelera (es decir, el comportamiento de Nautilus Move to Trash).

En caso de que exista dicho comando, también me interesaría saber de qué se trata.


2
Echa un vistazo a esta respuesta .
Peachy

Respuestas:


105

Puede usar el gvfs-trashcomando del paquete gvfs-binque está instalado por defecto en Ubuntu.

Mover archivo a la papelera:

gvfs-trash filename

Ver el contenido de la basura:

gvfs-ls trash://

Vaciar la basura:

gvfs-trash --empty

Visite también mi pregunta gvfs .
Pandya

Esta es la respuesta más simple para mí que funciona. Gracias.
Teody C. Seguin el

10
Según man gvfs-trashestá en desuso a favor de gio trash, ver man gio.
pbhj

67

Instalar trash-cliInstalar trash-cli -sudo apt-get install trash-cli

Ponga los archivos en la papelera con: trash file1 file2

Lista de archivos en la papelera: trash-list

Vaciar la basura con: trash-empty


1
Esa herramienta (relacionada con Ubuntu) apunta hacia una especificación de basura . Aunque bastante interesante, no estoy seguro de cuán ampliamente adoptado ...
Frank Nocke

Después de la instalación, ejecuto el comando y obtengo el error: File "/usr/bin/trash-list", line 4, in <module> ImportError: No module named 'trashcli'
Daniel

25

A partir de 2017, gvfs-trashparece estar en desuso.

$ touch test
$ gvfs-trash test
This tool has been deprecated, use 'gio trash' instead.
See 'gio help trash' for more info.

Debe usar gio, específicamente

gio trash

Es la forma recomendada.


2
¿Podría vincular una fuente por gvfs-trashser obsoleta y qué gioes?
Melebius

1
Lamentablemente, no puedo proporcionar un enlace, pero esto es lo que intento usar gvfs-trash en Kubuntu 17.10: pastebin.com/HA4a1pbs
Eugen Tverdokhleb

1
Puede pegar el ejemplo aquí en su respuesta, sería suficiente para mí junto con el número de versión del sistema. Estoy usando 16.04 LTS y gvfs-trashes la única opción aquí.
Melebius el

Esta herramienta tiene muchas otras características interesantes. Me gusta el infocomando; Parece útil.
Raffi Khatchadourian

4

Actualizando @Radu Rădeanurespuesta. Como Ubuntu me dice que use gioen su lugar ...

Entonces, a la basura some_file(o carpeta) use

gio trash some_file

Para ir a usar el basurero

gio list trash://

Vaciar la basura

gio trash --empty

3

Me gustan las formas de baja tecnología lo mejor. Hice una carpeta .Tren mi directorio de inicio escribiendo:

mkdir ~/.Tr

y en lugar de usar rmpara eliminar archivos, muevo esos archivos al ~/.Trdirectorio escribiendo:

mv fileName ~/.Tr

Esta es una manera efectiva y simple de mantener el acceso a los archivos que cree que no desea con el beneficio adicional en mi caso de no jugar con las carpetas del sistema, ya que mis niveles de conocimiento de Ubuntu son bastante bajos y me preocupa lo que podría ser. fastidiar cuando me meto con las cosas del sistema. Si también tiene un nivel bajo, tenga en cuenta que el "." en el nombre del directorio lo convierte en un directorio oculto.


3

Una respuesta anterior menciona el comando gio trash, que está bien hasta donde llega. Sin embargo, en las máquinas del servidor, no hay equivalente de un directorio de basura. He escrito un script Bash que hace el trabajo; en máquinas de escritorio (Ubuntu), usa gio trash. (He agregado alias tt='move-to-trash'a mi archivo de definiciones de alias; ttes un mnemotécnico para "desechar").

#!/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

En KDE 4.14.8 utilicé el siguiente comando para mover archivos a la papelera (como si se hubiera eliminado en Dolphin):

kioclient move path_to_file_or_directory_to_be_removed trash:/

Apéndice: encontré sobre el comando con

    ktrash --help
...
    Note: to move files to the trash, do not use ktrash, but "kioclient move 'url' trash:/"
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.