Linuxでファイルの中身を空にする方法

Linuxファイルを空にする方法でよい方法ないですか?って聞かれたので

君のためにLinux上でのやり方を残しておきます。

目次

主な用途

主な用途はずばり、 ログローテーション時にパーミッションが変えたくないって場面です。

mvコマンドでログコマンドを退避した後にログ書き込みが発生すると

変更したのにログのパーミッションが戻ってしまう。

以下、この方法をやらないと問題となるイメージです。

[root@rhel73-12201 log]# mv messages messages_20170920
[root@rhel73-12201 log]# ls -l messages*
-rw-r--r--. 1 root root 138611 9月 22 22:20 messages_20170920

パーミッションを644にしといたのに、ログが出力されると。。。

[root@rhel73-12201 log]$ ls -ltr messages*
-rw-r--r--. 1 root root 138611 9月 22 22:20 messages_20170920
-rw-------. 1 root root 105449 9月 22 22:30 messages

644に変えておいたパーミッションがかわってしまってではないか!

これを解消するためには、

  1. cpコマンドでファイルを退避
  2. 対象ファイルを空データにする

必要があります。 他にもっと良い方法があったら教えてね。

cp /dev/null filename

最もポピュラーな書き方が↓です。直観的でわかりやすい!

cp /dev/null filename 

↓が実行ログ。

[root@rhel73-12201 log]# ls -l messages*
-rw-r--r--. 1 root root 138611 9月 22 22:15 messages
[root@rhel73-12201 log]# cp messages messages_20170920
[root@rhel73-12201 log]# cp /dev/null messages
cp: `messages' を上書きしますか? yes
[root@rhel73-12201 log]# ls -l messages*
-rw-r--r--. 1 root root 0 9月 22 22:17 messages
-rw-r--r--. 1 root root 138611 9月 22 22:17 messages_20170920
[root@rhel73-12201 log]#

echo -n > filename

たまにある書き方が↓です。この書き方好きじゃない。

echo -n > filename 

↓が実行ログ。

[root@rhel73-12201 log]# ls -l messages*
-rw-r--r--. 1 root root 138611 9月 22 22:17 messages
[root@rhel73-12201 log]# cp messages messages_20170920
[root@rhel73-12201 log]# echo -n > messages
[root@rhel73-12201 log]# ls -l messages*
-rw-r--r--. 1 root root 0 9月 22 22:22 messages
-rw-r--r--. 1 root root 138611 9月 22 22:20 messages_20170920
[root@rhel73-12201 log]#

[改訂第3版]Linuxコマンドポケットリファレンスposted with ヨメレバ

沓名亮典 技術評論社 2015年06月

Amazon

Kindle

楽天ブックス

7net

honto

e-hon

紀伊國屋書店

よかったらシェアしてね!
  • URLをコピーしました!
目次