Last active
September 1, 2021 03:09
-
-
Save manse/af90cf9b4d90ebaddab2 to your computer and use it in GitHub Desktop.
Print disk usage on PHP. for motd.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$result = shell_exec('df -k'); | |
$disks = explode("\n", $result); | |
array_shift($disks); | |
function readable_byte($byte) { | |
$units = array('KB', 'MB', 'GB', 'TB'); | |
for ($i = 0; $i < 3; $i++) { | |
if ($byte < 1000) break; | |
$byte /= 1000; | |
} | |
return (floor($byte * 10) / 10) . $units[$i]; | |
} | |
$table = array(); | |
$color = array('1;37', '1;34', '1;32', '1;31', '1;33'); | |
foreach ($disks as $disk) { | |
$segments = preg_split('#\s+#', $disk); | |
if (count($segments) != 6 || $segments[0] === 'none' || !preg_match('#^/dev#', $segments[0])) continue; | |
$percent = intval($segments[2]) / intval($segments[1]); | |
$row = array(); | |
$row[] = $segments[0] . ' (' . $segments[5] . ')'; | |
$row[] = floor($percent * 100) . '%'; | |
$row[] = 'Free: ' . readable_byte($segments[3]); | |
$row[] = 'Used: ' . readable_byte($segments[2]); | |
$row[] = 'Total: ' . readable_byte($segments[1]); | |
$table[] = $row; | |
} | |
$col_width = array(); | |
foreach ($table as $row) { | |
foreach ($row as $i => $col) { | |
if (!isset($col_width[$i])) $col_width[$i] = 0; | |
$col_width[$i] = max(strlen($col), $col_width[$i]); | |
} | |
} | |
foreach ($table as $row) { | |
foreach ($row as $i => $col) { | |
if ($color[$i]) echo "\033[" . $color[$i] . 'm'; | |
echo $col . str_repeat(' ', $col_width[$i] - strlen($col)) . ' '; | |
if ($color[$i]) echo "\033[0m"; | |
} | |
echo "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment