LoginSignup
0
0

More than 3 years have passed since last update.

dfコマンド

Posted at

ディスクが満杯になる前にファイルを削除したい

※「シス環系女子 season2 第12話」の備忘録です。

dfコマンド

「Disk Free」の略。

以下実行結果の例

$ df
Filesystem    512-blocks      Used Available Capacity iused      ifree %iused  Mounted on
/dev/disk1s5   236568496  21796824  24231072    48%  487524 1182354956    0%   /
devfs                397       397         0   100%     688          0  100%   /dev
/dev/disk1s1   236568496 174417696  24231072    88%  885742 1181956738    0%   /System/Volumes/Data
/dev/disk1s4   236568496  14682840  24231072    38%       8 1182842472    0%   /private/var/vm
map auto_home          0         0         0   100%       0          0  100%   /System/Volumes/Data/home
/dev/disk1s3   236568496   1031416  24231072     5%      40 1182842440    0%   /Volumes/Recovery

左から、ディスクの名前、ディスクの総容量(単位:Kバイト)、使用量(単位:Kバイト)、空き容量(単位:Kバイト)、使用率、ディレクトリーツリー内でのマウント位置。

以下、「/ 」ディレクトリの空き容量だけを抜き取るコマンド
※dfの出力は特定の1文字だけで区切られているわけじゃないからcutコマンドは使いにくい。

$ df / | sed -E -e "s/[^ ]+ +[^ ]+ +[^ ]+ +([^ ]+).+/\1/"
Available
24587184

で、シェルスクリプトとかで必要なのは空き容量の数値だけなので、以下のコマンドで数値だけに絞り込む。

$ df / | sed -E -e "s/[^ ]+ +[^ ]+ +[^ ]+ +([^ ]+).+/\1/" | tail -n 1
24586272

以下、ルートディレクトリ「/」の空き容量が、10Gバイト以下になっていたら、30日以前のファイルを削除するシェルスクリプト

#!/bin/bash
available_size=$(df / | sed -E -e "s/[^ ]+ +[^ ]+ +[^ ]+ +([^ ]+).+/\1/" | tail -n 1)
required_size=$((10 * 1000 * 1000))

if [ $available_size -lt $required_size ]
then
  files=$(find / -ctime +30)
  for file in $files
  do
    rm "$file"
  done
fi

※おまけ。以下-hオプションをつけると数値に単位が付いて見やすくなる
「-human-readable」

$ df -h
Filesystem      Size   Used  Avail Capacity iused      ifree %iused  Mounted on
/dev/disk1s5   113Gi   10Gi   12Gi    47%  487524 1182354956    0%   /
devfs          199Ki  199Ki    0Bi   100%     688          0  100%   /dev
/dev/disk1s1   113Gi   83Gi   12Gi    88%  885707 1181956773    0%   /System/Volumes/Data
/dev/disk1s4   113Gi  7.0Gi   12Gi    38%       8 1182842472    0%   /private/var/vm
map auto_home    0Bi    0Bi    0Bi   100%       0          0  100%   /System/Volumes/Data/home
/dev/disk1s3   113Gi  504Mi   12Gi     5%      40 1182842440    0%   /Volumes/Recovery
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0