”:>文件” VS>>文件”
“:>文件”和“>文件”之间有什么区别吗?
$ : > file.out
$ ls -l file.out
-rw-rw---- 1 user user 0 Mar 18 21:08 file.out
$ > file.out
$ ls -l file.out
-rw-rw---- 1 user user 0 Mar 18 21:08 file.out
Is there any differences between ": > file" and "> file"?
$ : > file.out
$ ls -l file.out
-rw-rw---- 1 user user 0 Mar 18 21:08 file.out
$ > file.out
$ ls -l file.out
-rw-rw---- 1 user user 0 Mar 18 21:08 file.out
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
:
是 shell 内置的 NO-OP 或 null 操作。所以,是的,将其定向到一个文件最终会得到一个空文件,就像不将任何内容定向到文件一样。我想,从某种意义上说,你的来源是一种不同的虚无,但结果是相同的。根据高级 Bash 脚本编写指南,“> file.out
" 公式在某些系统上不起作用。请注意,在这两种情况下(与“touch”不同),如果文件已存在,则文件内容将被替换为任何内容。
:
is the shell built-in NO-OP or null operation. So yeah, directing it to a file ends up with an empty file, as does directing nothing to a file. There's a sense, I suppose, in which your source is a different kind of nothing, but the result is the same. According to the advanced Bash scripting guide, the "> file.out
" formulation won't work on some systems.Note that in both cases (unlike "touch") the file contents will be replaced with nothing if the file already exists.
使用<代码>:> file.out对于非bash来说更可移植。例如,zsh 将默认的空命令定义为
cat
,而不是:
(除非在模拟模式下)。如果您最终需要使脚本与非 bash 的/bin/sh
一起工作(例如,*BSD 系统、任何闭源操作系统,甚至在某些 GNU/Linux 发行版上)现在,使用破折号的地方),如果您使用: > ,您的生活会更轻松。文件.out
Using
: > file.out
is more portable to non-bash. For instance, zsh defines the default null-command ascat
, not:
(unless in an emulation mode). If you ever end up needing to make the script work with a/bin/sh
which is not bash (eg, a *BSD system, any closed-source OS, or even on some GNU/Linux distributions now, where dash is used), you'll make your life easier if you use: > file.out
根据 POSIX,两者都可以工作,但是如果重定向失败,带有
:
的版本就会中止,而仅带有重定向的版本只会返回非零退出状态。在后一种情况下,使用true
更具可移植性。Bash 仅在 POSIX 模式下才能正确执行此操作。
名为
:
的别名或函数违反了应用程序的 POSIX 约束,并且不可移植。According to POSIX, both work but the version with
:
aborts if the redirection fails while the version with just the redirection just returns a non-zero exit status. In the latter case it is more portable to usetrue
.Bash only does this right in POSIX mode.
Aliases or functions named
:
violate a POSIX constraint on the application and are not portable.我能想到的唯一区别是您可以通过别名或函数定义重新定义
:
。例如,您可能希望在大多数情况下截断文件(使用:
默认的不执行任何操作的行为),但在某些情况下强制文件具有标准标头。形式> file
无法重新定义。例如:
The only difference I can think of is that you can redefine
:
via alias or function definitions. For example, you may want to truncate files most of the time (using the default do-nothing behavior of:
), but force files to have a standard header in some cases. The form> file
cannot be redefined.For example: