A short one today: here is a function to “delete” (read: move) a file to the macOS Trash (Bin), as a safer alternative to rm.
I place this in my .zshrc but you can place it in a script if you prefer. This way I can call del *.log instead of rm *.log, and in the event I make a mistake, I can open Finder and hit Command-z to undo.
function del() {
if [[ $# ]]; then
a=()
for f in "$@"; do
a+=("$(realpath "$f")")
done
f=$(printf "\",POSIX file \"%s" "${a[@]}")\"
osascript -ss -e"tell app \"Finder\" to delete {${f:2}}" 1>/dev/null
fi
}
I saw something similar in this question “How to move files to trash from command line?” on StackExchange, but I think my method is safer and works for both files and folders. The trick is to:
- resolve input filenames into full physical paths using
realpath, - join the resulting array of paths with a
POSIX filedelimiter usingprintf, and - use AppleScript to tell Finder to delete all the specified
POSIX file(s).
Be warned: I’ve not tested the code when specifying a large number of files, and as usual, there is no error handling! Remember never to blindly run anything you find on the Internet. :)