What is the safest way to empty a directory in *ni

2020-07-11 09:42发布

I'm scared that one day, I'm going to put a space or miss out something in the command I currently use:

rm -rf ./*

Is there a safer way of emptying the current directory's contents?

13条回答
可以哭但决不认输i
2楼-- · 2020-07-11 09:56

Here are the alias I am using on macOS. It would ask for every rm command before executing.

# ~/.profile

function saferm() {
    echo rm "$@" 
    echo "" 
    read -p "* execute rm (y/n)? :  " yesorno

    if [ $yesorno == "y" ]; then
         /bin/rm "$@"
    fi
}

alias srm=saferm
alias rm=srm
查看更多
地球回转人心会变
3楼-- · 2020-07-11 10:03

You could drop the `f' switch and it should prompt you for each file to make sure you really want to remove it.

查看更多
SAY GOODBYE
4楼-- · 2020-07-11 10:04

I think this is a reasonable way:

find . -maxdepth 1 \! -name . -print0 | xargs -0 rm -rf

and it will also take care of hidden files and directories. The slash isn't required after the dot and this then will also eliminate the possible accident of typing . /.

Now if you are worried what it will delete, just change it into

find . -maxdepth 1 \! -name . -print  | less

And look at the list. Now you can put it into a function:

function enum_files { find . -maxdepth 1 \! -name . "$@"; }

And now your remove is safe:

enum_files | less                     # view the files
enum_files -print0 | xargs -0 rm -rf  # remove the files

If you are not in the habit of having embedded new-lines in filenames, you can omit the -print0 and -0 parameters. But i would use them, just in case :)

查看更多
甜甜的少女心
5楼-- · 2020-07-11 10:04

Go one level up and type in the directory name

rm -rf <dir>/*
查看更多
女痞
6楼-- · 2020-07-11 10:09

Use the trash command. In Debian/Ubuntu/etc., it can be installed from the package trash-cli. It works on both files and directories (since it's really moving the file, rather than immediately deleting it).

trash implements the freedesktop.org trash specification, compatible with the GNOME and KDE trash.

Files can be undeleted using restore-trash from the same package, or through the usual GUI.

查看更多
神经病院院长
7楼-- · 2020-07-11 10:11

I use one of:

rm -fr .

cd ..; rm -fr name-of-subdirectory

I'm seldom sufficiently attached to a directory that I want to get rid of the contents but must keep the directory itself.

查看更多
登录 后发表回答