shell 中 rm 和 unlink 的区别是什么?什么情况下只能用 unlink 而不能用 rm ?

shell 中 rmunlink 的区别是什么?

什么情况下只能用 unlink 而不能用 rm ?

阅读 7.5k
2 个回答

rm 和 unlink 命令都使用了 unlink 函数,但 rm 的功能更丰富一些,比如 rm 可以删除文件夹,但 unlink 就不行。

strace 跑 rm 與 unlink,結果有不同地方.

  1. strace rm 1.txt 片段

access("1.txt", W_OK) = 0

unlinkat(AT_FDCWD, "1.txt", 0) = 0

  1. strace unlink 2.txt 片段

unlink("2.txt") = 0

我想可以再看看 unlink 與 unlinkat 的 manpage 說明應該有答案 ? :)

   The  unlinkat() system call operates in exactly the same way as either unlink(2) or rmdir(2) (depending on

   whether or not flags includes the AT_REMOVEDIR flag) except for the differences described in  this  manual

   page.



   AT_REMOVEDIR

          By default, unlinkat() performs the equivalent of unlink(2) on pathname.  If the AT_REMOVEDIR  flag

          is specified, then performs the equivalent of rmdir(2) on pathname.


測試用 strace rm -r testdir 方式刪除一個目錄與其下的檔案目錄,結果為:

access("testdir", W_OK) = 0

unlinkat(AT_FDCWD, "testdir", AT_REMOVEDIR) = 0

所以結論一般命令用 rm 或是 unlink 都可以刪除檔案,因為都是一樣的意思。系統面呼叫來說刪除檔案一般還是使用 unlink() 呼叫,只是有另外提供 unlinkat 提供相同機制,但是可以刪除檔案或是空目錄。

不過我想其他系統的 rm 與 unlink 是有差異的,比方 solaris 就不一樣。

-bash-3.00$ uname -a

SunOS solaris 5.10 Generic_118855-33 i86pc i386 i86pc

man unlink :

System Administration Commands link(1M)

NAME

 link, unlink - link and unlink files and directories


SYNOPSIS

 /usr/sbin/link  existing-file new-file



 /usr/xpg4/bin/link  existing-file new-file



 /usr/sbin/unlink  file


DESCRIPTION

 The link and unlink  commands  link  and  unlink  files  and

 directories.  Only  super-users  can  use  these commands on

 directories.


我想詳細部份需要自行測試:p

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题