Linuxでファイルを空にする5つの方法

ログファイルを空にしたいときなど、いつも忘れるので・・・。

: > file

% : > file

これが一番シンプルですね。 : という区切りのコマンドがあり、それを file にリダイレクトしてあげるとファイルが空になります。man bash には以下のように記述されています。おそらくzshでは一番シンプルです。

・・・ A : separates the event specification from the word designator. ・・・



SHELL BUILTIN COMMANDS
Unless otherwise noted, each builtin command documented in this section as accepting options preceded by - accepts -- to signify the end of the options. For example, the :, true, false, and test builtins do not accept options. Also, please note that while executing in non-inter-active mode and while in posix mode, any special builtin (like ., :, break, continue, eval, exec, exit, export, readonly, return, set, shift, source, times, trap, unset) exiting with a non-zero status causes the shell to stop execution.
: [arguments]
No effect; the command does nothing beyond expanding arguments and performing any speci-fied redirections. A zero exit code is returned.


cp /dev/null file

% cp /dev/null file

/dev/null という擬似デバイスを利用して file を空にする方法です。
参考
-/dev/null - Wikipedia

echo -n > file

% echo -n > file

-n オプションがないと改行が入ってしまいます。
参考
-空のファイルを作成するには
-http://www.linux.or.jp/JM/html/GNU_sh-utils/man1/echo.1.html

cat > file

% cat > file

その後 ctrl-D や ctrl-C などで抜ける。

> file

% > file

単なるリダイレクトでもできますが、zshの場合、cat > と同じように、その後 ctrl-D や ctrl-C などで抜ける必要があります。bashはCtrl-Dは必要ないので、bashでは一番シンプルかもしれせん。

実験環境

OS CentOS 5
シェル zsh

まとめ

タイトルに5つの方法と書きましたが、もっと他にあると思いますので、教えて下さい><