Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test for GNU or BSD version of rm?

Tags:

bash

shell

gnu

bsd

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
like image 806
Kevin Burke Avatar asked Jul 26 '11 17:07

Kevin Burke


4 Answers

strings /bin/rm | grep -q 'GNU coreutils'

if $? is 0, it is coreutils

like image 76
frankc Avatar answered Oct 21 '22 22:10

frankc


I would recommend not starting down this road at all. Target your scripts to be as portable as possible, and only rely on flags/options/behaviors you can count on. Shell scripting is hard enough - why add more room for error?

To get a sense of the kind of thing I have in mind, check out Ryan Tomayko's Shell Haters talk. He also has a very well-organized page with links to POSIX descriptions of shell features and utilities. Here's rm, for example.

like image 28
Telemachus Avatar answered Oct 21 '22 21:10

Telemachus


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
like image 45
CharlesB Avatar answered Oct 21 '22 20:10

CharlesB


You could always ask rm its version with --version and check to see if it says gnu or coreutils like this:

rm --version 2>&1 | grep -i gnu &> /dev/null
[ $? -eq 0 ] && alias rm="rm -I"
like image 28
Corey Henderson Avatar answered Oct 21 '22 20:10

Corey Henderson