开发者_运维百科file\" and \"> file\"? $ : > file.out $ ls -l file.out" />
开发者

": > file" VS "> file"

开发者 https://www.devze.com 2022-12-23 03:50 出处:网络
Is there any differences between \": > 开发者_运维百科file\" and \"> file\"? $ : > file.out $ ls -l 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


: 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.


Using : > file.out is more portable to non-bash. For instance, zsh defines the default null-command as cat, 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


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 use true.

Bash only does this right in POSIX mode.

Aliases or functions named : violate a POSIX constraint on the application and are not portable.


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:

#! /bin/bash

test -n "$ADD_COPYRIGHT" &&
  :() { echo "# Copyright (c) 2010 MyName"; echo; }

# Truncate the file to zero size, unless ADD_COPYRIGHT is set, in which case
# the file is truncated to contain only a copyright notice.
: > file

# Add content to the file
some_command >> file
0

精彩评论

暂无评论...
验证码 换一张
取 消