1、問題描述
咱們在進行文件操做時常常會用到覆蓋輸出重定向(>),追加輸出重定向(>>),很明顯的看出兩種輸出重定向的符號相差不是很大,可是兩種的意義卻又很大的差異:前者是會覆蓋文件的內容的,然後者並不會覆蓋文件的內容!咱們在使用追加輸出重定向時極有可能因爲本身的不當心而使用覆蓋重定向,從而致使文件內容的丟失,可是linux系統仍是能夠解決這種問題的。
2、問題演示
[root@hpf-linux~]# echo "cangls" > /root/test.txt
[root@hpf-linux~]# cat /root/test.txt
cangls
[root@hpf-linux~]# echo "longls" > /root/test.txt
[root@hpf-linux~]# cat /root/test.txt
longls
[root@hpf-linux~]# echo "cangls" >> /root/test.txt
[root@hpf-linux~]# cat /root/test.txt
longls
cangls
經過上例能夠很明顯的看到使用>覆蓋輸出重定向會把文件test.txt的內容給刪除,而使用>>追加輸出輸出重定向並不會把文件的內容給弄丟失,下面介紹如何使用小技巧把這種問題儘量的杜絕。
3、技巧使用
set -C:禁止覆蓋重定向至已經存在的文件
set +C:關閉上述特性:
>|:在-C 特性下,強制使用覆蓋重定向
[root@hpf-linux~]# set -C
[root@hpf-linux~]# echo "xiaozels" > /root/test.txt
-bash: /root/test.txt: cannot overwrite existing file
[root@hpf-linux~]# echo "xiaozels" >> /root/test.txt
[root@hpf-linux~]# cat /root/test.txt
longls
cangls
xiaozels
[root@hpf-linux ~]# echo "xiaozels" >| /root/test.txt
[root@hpf-linux ~]# cat /root/test.txt
xiaozels
[root@hpf-linux ~]# set +C
[root@hpf-linux ~]# echo "bols" > /root/test.txt
[root@hpf-linux ~]# cat /root/test.txt
bols
經過上面的例子能夠看到使用set -C命令就能夠把覆蓋輸出重定向的功能給關閉,但有時候仍是要使用這功能咋辦?顯然能夠用set +C 命令就能夠了,但若咱們又忘記關閉了咋辦?顯然系統仍是有相應的辦法的,就是在使用覆蓋重定向時在後面加個|符號就能夠繼續使用覆蓋重定向的功能了。最後從此在遇到類是能夠改變文件內容的命令必定要當心!不要由於本身的一時大意而釀成沒必要要的後果!linux