Gio
Gio

Reputation: 3340

move file to ~/.trash, with unique filename

I have the following alias in my ~/.bashrc

alias del="mv -t ~/.trash"

This moves a file or directory to the ~/.trash folder. However, if I do the following:

del test.txt
touch test.txt
del test.txt

The second del call overwrites the already existing file test.txt in ~/.trash, hence I lose my backup. This is of course unwanted behaviour. I'm looking for a way to adapt my alias, so that a file which is moved to ~/.trash is appended with the date and time of the moment that is was moved there, hence resulting in an unique filename. Does somebody have an idea of how to do this? I'm looking for an easy way to adapt the alias, not an extensive bash script.

Upvotes: 4

Views: 420

Answers (3)

ikh
ikh

Reputation: 10417

Use mktemp --tmpdir.

$ alias del="mv -t \$(mktemp -d --tmpdir=$(echo ~)/.trash)"
$ touch test
$ del test
$ find ~/.trash
/home/username/.trash
/home/username/.trash/tmp.hJQTaEAx6Q
/home/username/.trash/tmp.hJQTaEAx6Q/test

Upvotes: 1

Zilicon
Zilicon

Reputation: 3860

I think i'd make a mini script instead of an alias

#!/bin/bash

DATE=$(date +%Y_%m_%d_%H_%M_%S)

for file; do
    mv "${file}" "${HOME}/.trash/${DATE}_${file}"
done

you can create the files in the trash with the file name before the date (but you'll loose the extension - although that's fixable too).

Just don't use the script multiple times for the same file names on the same second :) if you insist you can add nanoseconds to the date stamp.

Upvotes: -1

konsolebox
konsolebox

Reputation: 75558

You can use a function. Functions are also recommended over aliases.

function del {
    local F
    for F; do
        mv -- "$F" ~/.trash/"$F-$(exec date '+%F-%T')"
    done
}

Place it in .bashrc and make sure .bash_profile sources .bashrc as well.

See the date manual (man date) for other formats you can use.

Upvotes: 5

Related Questions