天行健,君子以自强不息;地势坤,君子以厚德载物;

sed -i 修改链接文件的注意事项

对一些系统软链文件用sed修改,才发现原来sed -i是不能直接修改软链接文件的,如下测试示例情况:

~ $  ln -s T/Test-A Test-B
~ $  ll
total 4
drwxr-xr-x 2 quwenqing quwenqing 4096 Feb 21 17:03 T/
lrwxrwxrwx 1 quwenqing quwenqing    8 Feb 21 17:03 Test-B -> T/Test-A
~ $  sed -i '/qwq/d' ./Test-B 
~ $  ll
total 8
drwxr-xr-x 2 quwenqing quwenqing 4096 Feb 21 17:03 T/
-rw-r--r-- 1 quwenqing quwenqing   45 Feb 21 17:05 Test-B
~ $ 

我们发现链接文件不再是链接文件了,后来查看sed man文档时发现如下选项说明

--follow-symlinks
follow symlinks when processing in place; hard links will still be broken.
-i[SUFFIX], --in-place[=SUFFIX]
edit files in place (makes backup if extension supplied). The default operation mode is to break symbolic and hard links. This can bechanged with --follow-symlinks and --copy.
-c, --copy
use copy instead of rename when shuffling files in -i mode. While this will avoid breaking links (symbolic or hard), the resulting editing operation is not atomic. This is rarely the desired mode; --follow-symlinks is usually enough, and it is both faster and more secure.

以上说明就不作过多解释了,说的很明显,看下面实例

~ $  ln -s T/Test-A Test-B
~ $  ll
total 4
drwxr-xr-x 2 quwenqing quwenqing 4096 Feb 21 17:12 T/
lrwxrwxrwx 1 quwenqing quwenqing    8 Feb 21 17:12 Test-B -> T/Test-A
~ $  sed -i -c '/qwq/d' ./Test-B 
~ $  ll
total 8
-rw-r--r-- 1 quwenqing quwenqing   45 Feb 21 17:14 sed55WPuO
drwxr-xr-x 2 quwenqing quwenqing 4096 Feb 21 17:12 T/
lrwxrwxrwx 1 quwenqing quwenqing    8 Feb 21 17:12 Test-B -> T/Test-A
~ $  

--follow-symlinks选项只对软链接有效,硬链接还是会被破坏,建议使用-c选项,这里就不举例了

--follow-symlinks
follow symlinks when processing in place; hard links will still be broken.

注意:CentOS 5系列的还是使用老版本的sed,没有--follow-symlinks类似的选项,不会有此类问题,CentOS 6/7 均有该类情况。

点赞

发表评论