有时我们经常会用到某些路径,为了使用方便会建立快捷方式,且文件修改会同步。
在Windows系统中,快捷方式会随着源文件删除而时效,同理Linux系统中的软链接,但是如果采用硬链接方式,即便源文件删除,链接后的目标文件仍保留且可编写。
命令
ln [参数] 源文件或目录 目标文件或目录
【参数】
-s 建立软链接
-i 覆盖前先询问
-v 显示创建链接的过程
-f 强制创建链接
注:软链接的源文件或目录要写绝对目录,不然会报错。
现有/opt/test为我经常用的测试路径,我想把其快捷方式放到/miao/temp下,以便后续我直接在/miao路径下就能看到并修改相关文件。
ln -s /opt/test .
建立软连接,虽然目前路径仍显示为/miao/temp,但我们能看到test文件并能编写其下面的txt文件,且文件修改同步。
[root@localhost temp]# cd /opt [root@localhost opt]# ll 总用量 0 drwxr-xr-x 3 root 0 16 2月 22 15:35 soso drwxr-xr-x 2 root 0 6 2月 22 15:55 test [root@localhost opt]# cd /miao [root@localhost miao]# ll 总用量 4 drwxrwxrwx 10 lin lin 167 2月 19 11:19 elasticsearch-8.0.0 drwxrwxrwx 7 lin lin 4096 11月 6 2020 elasticsearch-head-master drwxr-xr-x 2 root 0 18 2月 22 15:59 temp drwxr-xr-x 2 root 0 6 2月 22 15:58 test [root@localhost miao]# cd temp [root@localhost temp]# ll 总用量 0 [root@localhost temp]# ln -s /opt/test . [root@localhost temp]# pwd /miao/temp [root@localhost temp]# ll 总用量 0 lrwxrwxrwx 1 root 0 9 2月 22 16:09 test -> /opt/test [root@localhost temp]# cd /opt/test [root@localhost test]# ll 总用量 4 -rw-r--r-- 1 root 0 8 2月 22 16:11 1.txt [root@localhost test]# more 1.txt abcdefg [root@localhost test]# cd /miao/temp/ [root@localhost temp]# ll 总用量 0 lrwxrwxrwx 1 root 0 9 2月 22 16:09 test -> /opt/test [root@localhost temp]# cd test [root@localhost test]# ll 总用量 4 -rw-r--r-- 1 root 0 8 2月 22 16:11 1.txt [root@localhost test]# vi 1.txt [root@localhost test]# more 1.txt abcdefg hijklmn [root@localhost test]# more /opt/test/1.txt abcdefg hijklmn [root@localhost test]#
如软连接需要修改要怎样处理?我现在不想用/opt/test,以后测试文件我都会放到/miao/test里,命令如下:
ln -snf /miao/test .
是一样的,因为..表示上一级目录,.表示当前目录。
[root@localhost miao]# ll 总用量 4 drwxrwxrwx 10 lin lin 167 2月 19 11:19 elasticsearch-8.0.0 drwxrwxrwx 7 lin lin 4096 11月 6 2020 elasticsearch-head-master drwxr-xr-x 2 root 0 18 2月 22 16:09 temp drwxr-xr-x 2 root 0 6 2月 22 15:58 test [root@localhost miao]# cd temp/ [root@localhost temp]# ll 总用量 0 lrwxrwxrwx 1 root 0 9 2月 22 16:09 test -> /opt/test [root@localhost temp]# ln -snf /miao/test . [root@localhost temp]# ll 总用量 0 lrwxrwxrwx 1 root 0 7 2月 22 16:19 test -> ../test [root@localhost temp]#
如果后续因为空间不足需要清理文件,删除此软连接,跟删除目录文件的命令一样。
[root@localhost temp]# rm -rf test [root@localhost temp]# ll 总用量 0 [root@localhost temp]#