GNU 版本的
rm
有一个很酷的 -I 标志。从联机帮助页:
-I prompt once before removing more than three files, or when removing recursively. Less
intrusive than -i, while still giving protection against most mistakes
Mac 没有:
$ rm -I scratch
rm: illegal option -- I
usage: rm [-f | -i] [-dPRrvW] file ...
unlink file
有时人们在 Mac 上安装了
coreutils
(GNU 版本),有时却没有。有没有办法在继续之前检测此命令行标志?我想在我的 bash_profile 中有这样的东西:
if [ has_gnu_rm_version ]; then
alias rm="rm -I"
fi
strings /bin/rm | grep -q 'GNU coreutils'
如果$?是0,就是coreutils
我建议根本不要走这条路。将您的脚本定位为尽可能可移植,并且仅依赖于您可以信赖的标志/选项/行为。 Shell 脚本编写已经够难了 - 为什么还要增加更多的出错空间?
您可以查看POSIX 官方网站了解其实用命令的规范。例如,rm。
我想说在临时文件上测试
rm -I
的输出,如果通过则使用别名
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
您可以随时使用
--version
询问 rm 其版本,并检查它是否显示 gnu 或 coreutils,如下所示:
rm --version 2>&1 | grep -i gnu &> /dev/null
[ $? -eq 0 ] && alias rm="rm -I"
这样的事情怎么样?
#!/bin/bash
rm -I &> /dev/null
if [ "$?" == "0" ]; then
echo coreutils detected
else
echo bsd version detected
fi