linux入门之软硬链接

linux系统下有两种链接方式,软链接和硬链接,软链接可以看成是windows中的快捷方式,可以让你快速链接到目标档案或目录;硬链接则透过文件系统的inode来产生新的文件名而不改变inode号。

inode

分清两者之前的区别,首先需要先了解inode即索引节点这个概念。当划分磁盘分区并格式化的时候,整个分区会被划分为两个部分,inode和data block。block 是文件系统的最小存储单位,主要用于存储数据,inode是文件系统的唯一标识,想要访问这个文件的时候必须要找到它的inode号,inode号里边包含文件的类型,权限,时间戳,owner,group,链接数,大小以及扩展属性还有block指针。一个文件只有一个 inode,可以有多个block。

目录

对于一个目录而言,在linux下,目录也是“文件”,目录存储inode和元数据,目录的  block存储名字和inode号。

  •  文件引用一个是inode号
  • 人是通过文件名来引用一个文件
  • 一个目录是目录下的文件名和文件inode号之间的映射

各种命令和inode的关系

1 、cp和inode

    使用cp命令时,系统会为该文件分配一个空闲的inode号,在inode表中生成新的目录项,将名称与inode编号关联并进行拷贝。

[root@localhost ~]# cp ws.txt 55.txt
cp: overwrite `55.txt'? y
[root@localhost ~]# cat 55.txt
we have a big dream,my dream is 
[root@localhost ~]# ls -i ws.txt
146114 ws.txt
[root@localhost ~]# ls-i 55.txt
-bash: ls-i: command not found
[root@localhost ~]# ls -i 55.txt
146118 55.txt

 

2、 rm和inode

使用rm命令的本质是减少文件的硬链接数,当硬链接数减为0时,如果另一个文件需要使用数据块则直接覆盖,不使用时不会删除,把数据放在空闲列表中。

[root@localhost ~]# ll ws.txt
-rw-r--r--. 1 root root 33 Jul 17 17:09 ws.txt
[root@localhost ~]# rm ws.txt
rm: remove regular file `ws.txt'? y
[root@localhost ~]# ll ws.txt
ls: cannot access ws.txt: No such file or directory

 

3、mv和inode

mv命令的目标和源在相同的文件系统,作为mv命令用新的文件名创建对应新的目录项,删除旧的目录条对应的旧的文件名,不影响inode表的数据位置,数据不移动。

如果目标和源不在同一个文件系统,mv相当与cp和rm

[root@localhost ~]# mv 55.txt wx.txt
[root@localhost ~]# cat 55.txt
cat: 55.txt: No such file or directory 
[root@localhost ~]# cat wx.txt  
we have a big dream,my dream is 

 

硬链接

 创建硬链接会增加额外的记录项以引用文件

对应于同一文件系统上一个物理文件

每个目录引用相同的inode号

创建时链接数递增

删除文件时: rm命令递减计数的链接 文件要存在,至少有一个链接数 当链接数为零时,该文件被删除不能跨越驱动器或分区

语法: ln filename  [ linkname ]

[root@localhost ~]# ln wx.txt 55.txt
[root@localhost ~]# cat wx.txt
we have a big dream,my dream is 
[root@localhost ~]# cat 55.txt
we have a big dream,my dream is 
[root@localhost ~]# ls -i wx.txt
146118 wx.txt
[root@localhost ~]# ls -i 55.txt
146118 55

 

软链接

  • 一个符号链接指向另一个文件
  • ls - l的 显示链接的名称和引用的文件
  • 一个符号链接的内容是它引用文件的名称
  • 删除源时,软链接不可用
  •   可以跨分区
  • 指向的是另一个文件的路径;其大小为指向的路径字符串的长度;不增加或减少目标文件inode的 引用计数;

     语法: ln -s  filename  [linkname]

[root@localhost ~]# ln -s 57.txt 55.txt  
[root@localhost ~]# cat 55.txt
we have a big dream,my dream is 
[root@localhost ~]# cat 57.txt
we have a big dream,my dream is 
[root@localhost ~]# rm 57.txt
rm: remove regular file `57.txt'? y
[root@localhost ~]# cat 55.txt
cat: 55.txt: No such file or directory

删除后文件颜色发生变化并闪烁,如图

 

[AZ}C%]98@`AX]EUM}YH~[O



 

posted @ 2018-07-17 19:03  www岩  阅读(210)  评论(0编辑  收藏  举报