Skip to main content
3 of 4
added 87 characters in body
Kusalananda
  • 355.8k
  • 42
  • 735
  • 1.1k

An alias can not take arguments and use $@ to access them like that.

If you have alias rm ='something something', then using rm file1 file2 would execute

something something file1 file2

and if the alias included $@, this would be expanded with the command line arguments of the shell, not of the alias.

In your case, assuming the shell's list of command line arguments is empty, the alias

alias rm='cp $@ /tmp/recycle_bin && rm $@'

would execute as

cp /tmp/recycle_bin && rm file1 file2

when invoked as rm file1 file2. The cp utility will complain about only having a single operand.


You could use a shell function instead:

rm () {
    cp -- "$@" "${TMPDIR:-/tmp}/recycle_bin" &&
    command rm -- "$@"
}

This would copy the indicated files to $TMPDIR/recycle_bin (or /tmp/recycle_bin if TMPDIR is unset or empty) and then delete the files. The command command is used to not cause an infinite recursion. The -- are needed to treat all arguments as filenames rather than as options.

A bit more efficient (cp+rm == mv):

rm () {
    mv -- "$@" "${TMPDIR:-/tmp}/recycle_bin"
}

A bit more safe (creates the recycle bin if it's not there):

rm () {
    mkdir -p "${TMPDIR:-/tmp}/recycle_bin" &&
    mv -- "$@" "${TMPDIR:-/tmp}/recycle_bin"
}

And even safer, with GNU mv (creates backups in the recycle bin if name collisions occur):

rm () {
    mkdir -p "${TMPDIR:-/tmp}/recycle_bin" &&
    mv -b -- "$@" "${TMPDIR:-/tmp}/recycle_bin"
}

For an alias-only (and GNU-only) variation, see "https://unix.stackexchange.com/questions/452496".

Kusalananda
  • 355.8k
  • 42
  • 735
  • 1.1k