Question

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
Was it helpful?

Solution

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

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top