プログラマ 福重 伸太朗 〜基本へ帰ろう〜 このページをアンテナに追加 RSSフィード

2010-02-12

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 オプションがないと改行が入ってしまいます。

参考

-空のファイルを作成するには

-404 - エラー: 404


cat > file

% cat > file

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


> file

% > file

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


実験環境

OS CentOS 5
シェル zsh

スペシャルサンクス

Twitterで色々教えて頂きました。感謝ですm(_ _)m


まとめ

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

uniomuniom 2010/03/23 13:17 bashなのですが、cat /dev/null > file
でやってます。

japanrockjapanrock 2010/03/23 16:09 id:uniomさん
zshでも cat /dev/null > file いけました!ありがとうございます!

スパム対策のためのダミーです。もし見えても何も入力しないでください
ゲスト


画像認証