【BASH】如何防止在重定向时覆盖现有文件
通常我们都不希望因为操作失误而错误的删除文件,但在使用重定向保存结果的时候却很容易出现这种情况。那么如何解决呢?
通过shell
通过设定bash的选项noclobber,在默认的情况下,这个选项是打开的
set -o noclobber
noclobber
这个选项告诉bash在重定向的时候不要覆盖已有文件。
看下面的例子
把这个选项关掉
$ set +o noclobber
$ echo something > my.file
$ echo some more > my.file
打开这个选项
$ set -o noclobber
$ echo something > my.file
bash: my.file: cannot overwrite existing file
$ echo some more >> my.file
$
可以看到在打开这个选项的时候,如果重定向到已有文件,bash会提示出错。
不过记住,这个选项不是万能的,它只是bash自己使用的选项而已
请看下面的这个例子
$ echo useless data > some.file
$ echo important data > other.file
$ set -o noclobber
$ cp some.file other.file
$
这个选项对于cp就是没有效果的。
如果你觉得这个选项不重要,思考下如果重定向的文件名是由正则表达式生成的,或者是通过参数传递给你的脚本。