bashshellgnubsd

How to test for GNU or BSD version of rm?


The GNU version of rm has a cool -I flag. From the manpage:

-I     prompt once before removing more than three files, or when removing recursively.   Less
          intrusive than -i, while still giving protection against most mistakes

Macs don't:

$ rm -I scratch
rm: illegal option -- I
usage: rm [-f | -i] [-dPRrvW] file ...
   unlink file

Sometimes people have coreutils (the GNU version) installed on Macs and sometimes they don't. Is there a way to detect this command line flag before proceeding? I'd like to have something like this in my bash_profile:

if [ has_gnu_rm_version ]; then
    alias rm="rm -I"
fi

Solution

  • I'd say test the output of rm -I on a temp file, if it passes then use the alias

    touch /tmp/my_core_util_check
    
    if rm -I /tmp/my_core_util_check > /dev/null 2>&1 ; then
        alias rm="rm -I"
    else
        rm /tmp/my_core_util_check;
    fi