为什么在 Linux 中使用“ln -sf”?

cas*_*mia 28 shell ln

我有2个问题。第一个用于-sf选项,第二个用于更具体的-f选项用法。

通过谷歌搜索,我找到了 command ln、 option-s和-f.

(从http://linux.about.com/od/commands/l/blcmdl1_ln.htm复制)

-s, --symbolic : make symbolic links instead of hard links
-f, --force : remove existing destination files
Run Code Online (Sandbox Code Playgroud)

我分别理解这些选项。但是,如何同时使用 this-s和-foptions 呢?-s用于创建链接文件,-f用于删除链接文件。为什么要使用这个合并选项?

为了更多地了解ln命令,我做了一些例子。

$ touch foo     # create sample file
$ ln -s foo bar # make link to file
$ vim bar       # check how link file works: foo file opened
$ ln -f bar     # remove link file 
Run Code Online (Sandbox Code Playgroud)

在下一个命令之前一切正常

$ ln -s foo foobar
$ ln -f foo     # remove original file
Run Code Online (Sandbox Code Playgroud)

根据-f选项的描述,最后一个命令应该不起作用,但它起作用了!foo已移除。

为什么会这样?

ter*_*don 48

首先,要查找命令选项的作用,您可以使用man command. 所以,如果你运行man ln,你会看到:

   -f, --force
          remove existing destination files

   -s, --symbolic
          make symbolic links instead of hard links
Run Code Online (Sandbox Code Playgroud)

现在,-s正如您所说,是使链接具有符号性而不是硬链接。的-f,但是,是不是要删除链接。如果目标文件存在,则覆盖目标文件。为了显示:

 $ ls -l
total 0
-rw-r--r-- 1 terdon terdon 0 Mar 26 13:18 bar
-rw-r--r-- 1 terdon terdon 0 Mar 26 13:18 foo

$ ln -s foo bar  ## fails because the target exists
ln: failed to create symbolic link ‘bar’: File exists

$ ln -sf foo bar   ## Works because bar is removed and replaced with the link
$ ls -l
total 0
lrwxrwxrwx 1 terdon terdon 3 Mar 26 13:19 bar -> foo
-rw-r--r-- 1 terdon terdon 0 Mar 26 13:18 foo
Run Code Online (Sandbox Code Playgroud)