Search code examples
macosbashrm

How to auto cancel deleting while rm asking for confirm?


Is there something like rm -f but auto n not auto y? To delete what can be deleted rm not asked and prevent others being deleted. Like files with read-only flag, files opened by other program. I tried yes n | rm somefile not working.

It's OS X 10.11. rm promotes on read-only files.

Seems rm has different default behavior on different platform.

Answers I've tried on OS X 10.11 and Ubuntu 14.04 (not work):

rm somefile
rm --interactive=never somefile 
echo n| rm -i somefile

Ubuntu log:

$ touch somefile
$ chmod 444 somefile 
$ ls -l somefile 
-r--r--r-- 1 ubuntu ubuntu 0 Apr 12 06:04 somefile
$ 
$ rm somefile
rm: remove write-protected regular empty file ‘somefile’? n
$ rm somefile
rm: remove write-protected regular empty file ‘somefile’? n
$ 
$ rm --interactive=never somefile 
$ rm --interactive=never somefile 
rm: cannot remove ‘somefile’: No such file or directory
$ 
$ touch somefile                                                
$ chmod 444 somefile                                                 
$ ls -l somefile                                            
-r--r--r-- 1 ubuntu ubuntu 0 Apr 12 06:06 somefile
$ echo n| rm -i somefile 
rm: remove write-protected regular empty file ‘somefile’? $ ls -l somefile 
-r--r--r-- 1 ubuntu ubuntu 0 Apr 12 06:06 somefile

@SaintHax's solution

for file in $@; do
    [ -w $file ] && rm $file
done

works with read only files on platforms mentioned above.


Solution

  • This works fine for me on my two flavors of Linux.

    echo n| rm -i *.csv
    

    However, -i is always interactive, so it basically negates the command. If you want to skip anything with the readonly command, I'd suggest creating a function.

    del() {
       for file in $@; do
          [ -w $file ] && rm $file
       done
    } 
    

    Note, that this only works if the files are not writable by you.