Search code examples
linuxbashshellrm

prompt list of files before execution of rm


I started using "sudo rm -r" to delete files/directories. I even put it as an alias of rm.

I normally know what I am doing and I am quite experience linux user.

However, I would like that when I press the "ENTER", before the execution of rm, a list of files will show up on the screen and a prompt at the end to OK the deletion of files.

Options -i -I -v does not do what I want. I want only one prompt for all the printed files on screen.

Thank you.


Solution

  • ##
    # Double-check files to delete.
    delcheck() {
      printf 'Here are the %d files you said you wanted to delete:\n' "$#"
      printf '"%s"\n' "$@"
      read -p 'Do you want to delete them? [y/N] ' doit
      case "$doit" in
        [yY]) rm "$@";;
        *) printf 'No files deleted\n';;
      esac
    }
    

    This is a shell function that (when used properly) will do what you want. However, if you load the function in your current shell then try to use it with sudo, it won't do what you expect because sudo creates a separate shell. So you'd need to make this a shell script…

    #!/bin/bash
    
    … same code as above …
    
    # All this script does is create the function and then execute it.
    # It's lazy, but functions are nice.
    delcheck "$@"
    

    …then make sure sudo can access it. Put it in some place that is in the sudo execution PATH (Depending on sudo configuration.) Then if you really want to execute it precisely as sudo rm -r * you will still need to name the script rm, (which in my opinion is dangerous) and make sure its PATH is before /bin in your PATH. (Also dangerous). But there you go.