在學習cp命令時我們會知道復制軟鏈接時,如果要保留鏈接文件使用-d,但當我們實際操作時卻常常出現如下
情況
[root@localhost ~]# ls -l /etc/redhat-release #此文件為鏈接文件 lrwxrwxrwx. 1 root root 14 Oct 17 08:48 /etc/redhat-release -> centos-release [root@localhost ~]# cp -d /etc/redhat-release /root/redhat.s #使用-d 保存鏈接文件屬性 [root@localhost ~]# ls -l /root/redhat.s #查看可知centos-release是閃爍的,也就是不存在 lrwxrwxrwx 1 root root 14 Oct 22 09:06 /root/redhat.s -> centos-release [root@localhost ~]# cat /root/redhat.s #看不了/root/redhat.s鏈接文件 cat: /root/redhat.s: No such file or directory
為什么我們使用cp -d 復制鏈接文件會失?。磕蔷鸵碿p -d 是如何復制軟鏈接的。在上例中,我們打算將
/etc/redhat-release軟鏈接復制到/root/redhat.s。在使用cp -d實際上是將原軟鏈接中指針區代表原文件
下面命令可以看出其文件大小都為14,即centos-release
路徑的字符串拷貝到新創建的/root/redhat.s中
字符串大小
[root@localhost ~]# ls -l /etc/redhat-release /root/redhat.s lrwxrwxrwx. 1 root root 14 Oct 17 08:48 /etc/redhat-release -> centos-release lrwxrwxrwx 1 root root 14 Oct 22 09:06 /root/redhat.s -> centos-release
當我們查看新建軟鏈接/root/redhat.s時看到原文件路徑是centos-release,就會到當前路徑(/root/)
上查看centos-release文件,而實際上原文件在/etc/目錄下,所以查看/root/redhat.s才會出現
/root/redhat.s: No such file or directory的錯誤。
根據這個原理我們可以推斷,如果原鏈接文件存的是原文件的絕對路徑的話,新建的鏈接文件就能找到原文件而不是報錯,接下來我們實驗一下。
#1. 先創建一個軟鏈接/etc/redhat-release2,可知數據區存的是原文件的絕對路徑/etc/centos-release [root@localhost ~]# ln -s /etc/centos-release /etc/redhat-release2 [root@localhost ~]# ls -l /etc/redhat-release2 lrwxrwxrwx 1 root root 19 Oct 22 09:37 /etc/redhat-release2 -> /etc/centos-release #2. 復制剛創建的軟鏈接/etc/redhat-release2到/root/radhat2.s [root@localhost ~]# cp -d /etc/redhat-release2 /root/radhat2.s [root@localhost ~]# ls -l /root/radhat2.s lrwxrwxrwx 1 root root 19 Oct 22 09:41 /root/radhat2.s -> /etc/centos-release #3. 查看新軟鏈接內容 [root@localhost ~]# cat /root/radhat2.s CentOS release 6.7 (Final)
cp -d 復制軟鏈接時總結
1. 當原鏈接文件中存的是原文件的絕對路徑:創建的新鏈接文件可在任何路徑下。 2. 當原鏈接文件中存的是原文件的相對路徑: 例1: 新鏈接文件在/root/link2 相對路徑是 centos (來自原鏈接文件的指針數據區) 那么/root/centos就是原文件路徑 例2: 新鏈接文件為/root/test/link2 相對路徑為../centos 那么/root/centos為原文件路徑 原文件路徑找得到就ok,找不到就報錯。
原創文章,作者:lirou,如若轉載,請注明出處:http://www.www58058.com/53450