Bash でファイルが空かどうか確認するにはどうすればいいですか? 質問する

Bash でファイルが空かどうか確認するにはどうすればいいですか? 質問する

diff.txtというファイルがあります。それが空かどうか確認したいです。

以下のような bash スクリプトを作成しましたが、動作しませんでした。

if [ -s diff.txt ]
then
        touch empty.txt
        rm full.txt
else
        touch full.txt
        rm emtpy.txt
fi

ベストアンサー1

これを試して:

#!/bin/bash -e

if [ -s diff.txt ]; then
        # The file is not-empty.
        rm -f empty.txt
        touch full.txt
else
        # The file is empty.
        rm -f full.txt
        touch empty.txt
fi

ちなみに、 @Matthias の提案どおり、empty.txtとの役割を入れ替えていることに注意してください。full.txt

おすすめ記事