使用echo; >和>>有什么区别

dep*_*ion 4 unix git syntax

我在git网站上遇到了这个问题:

mkdir log
echo '*.log' > log/.gitignore
git add log
echo tmp >> .gitignore
git add .gitignore
git commit -m "ignored log files and tmp dir"
Run Code Online (Sandbox Code Playgroud)

因此,在echo的第一个实例中,我们将字符串写入日志目录中的文件.gitignore。在第二种情况下,我们是否将tmp写入文件.gitignore(在当前目录中)。为什么我们需要使用>> vs>?

cas*_*tis 7

将某些内容回显到文件时,>>将附加到文件并>覆盖文件。

$ echo foobar > test
$ cat test
foobar
$ echo baz >> test
$ cat test
foobar
baz
$ echo foobar > test
$ cat test
foobar
Run Code Online (Sandbox Code Playgroud)

在您发布的示例中,创建了一个日志目录,然后*.log将其放入其中,log/.gitignore以便没有日志文件提交到git。自>使用以来,如果存在.gitignore文件,则仅使用会覆盖它*.log

然后将日志目录本身添加到本地git阶段。

在下一行中,>>添加,以便将tmp其附加到.gitignore文件的末尾而不是覆盖它。然后将其添加到暂存区域。


Ger*_*che 5

>是一个重定向运算符。< > >| << >> <& >& <<- <>都是shell命令解释器中的重定向操作符。

\n\n

在您的示例中,本质上>是覆盖和>>附加。

\n\n

请参阅man sh,(在您的终端上,您可以通过 访问手册man sh)。

\n\n
Redirections\n     Redirections are used to change where a command reads its input or sends its output.  In\n     general, redirections open, close, or duplicate an existing reference to a file.  The over\xe2\x80\x90\n     all format used for redirection is:\n\n           [n] redir-op file\n\n     where redir-op is one of the redirection operators mentioned previously.  Following is a\n     list of the possible redirections.  The [n] is an optional number, as in \'3\' (not \'[3]\'),\n     that refers to a file descriptor.\n\n           [n]> file   Redirect standard output (or n) to file.\n\n           [n]>| file  Same, but override the -C option.\n\n           [n]>> file  Append standard output (or n) to file.\n\n           [n]< file   Redirect standard input (or n) from file.\n\n           [n1]<&n2    Duplicate standard input (or n1) from file descriptor n2.\n\n           [n]<&-      Close standard input (or n).\n\n           [n1]>&n2    Duplicate standard output (or n1) to n2.\n\n           [n]>&-      Close standard output (or n).\n\n           [n]<> file  Open file for reading and writing on standard input (or n).\n\n     The following redirection is often called a "here-document".\n\n           [n]<< delimiter\n                 here-doc-text ...\n           delimiter\n\n     All the text on successive lines up to the delimiter is saved away and made available to the\n     command on standard input, or file descriptor n if it is specified.  If the delimiter as\n     specified on the initial line is quoted, then the here-doc-text is treated literally, other\xe2\x80\x90\n     wise the text is subjected to parameter expansion, command substitution, and arithmetic\n     expansion (as described in the section on "Expansions").  If the operator is "<<-" instead\n     of "<<", then leading tabs in the here-doc-text are stripped.\n
Run Code Online (Sandbox Code Playgroud)\n