shell提供了一种称为noclobber(
如set noclobber 明确声明不覆盖,clobber的单词有殴打,击打的意思)的特性,该特性可防止重定向时不经意地重写了已存在的文件。通过设置变量noclobber可以将此特性打开。打开后若将输出重定向到某个已存在文件,则shell将报告错误消息,并且不执行重定向命令。如果前面的示例产生了下面的消息之一,则设置了 noclobber特性。下面的示例首先打开noclobber特性,然后是将echo的输出重定向到已存在文件,最后是关闭noclobber特性。
$ set -o noclobber
$ echo "kick" > tmp
-bash: tmp: Cannot overwrite existing file
$ set +o noclobber
$ echo "kick" > tmp
$ echo "kick" > tmp
-bash: tmp: Cannot overwrite existing file
$ set +o noclobber
$ echo "kick" > tmp
我们也可以写一个简单的if语句的脚本来检查noclobber选项是否开启:
#!/bin/bash
# These lines will print a message if the noclobber option is set:
if [ ! -o noclobber ]
then
echo "Your files are not protected against accidental overwriting using redirection."
fi
# These lines will print a message if the noclobber option is set:
if [ ! -o noclobber ]
then
echo "Your files are not protected against accidental overwriting using redirection."
fi
# ./noclobber.sh
Your files are not protected against accidental overwriting using redirection.
Your files are not protected against accidental overwriting using redirection.
从输出可以看出,我并未开启noclobber选项。
本文转自 zhangzj1030 51CTO博客,原文链接:http://blog.51cto.com/tech110/232312