Thursday, October 26, 2017

Output Result from df Command STDOUT to HTML

An example of where we need this is to display the output from the command df to a webpage. All the spaces and newline are all disregarded by HTML so it will display as one long line.

PRE Block in HTML

Solution: Wrap output such as this in a pre block in HTML.
STORAGE=$(df -PTh | column -t | sort -n -k6n)
echo "<pre>$STORAGE</pre>"
Though, HTML does not take care of preserving white space

To preserve the white space

In the output of the command chain is white space in the form of spaces and newlines (and you are lucky there are no tabs). You should make pipe the output into | sed 's/ /&nbsp;/g' | sed 's/^/<br>/':
STORAGE=$(df -PTh | column -t | sort -n -k6n)| sed 's/ /&nbsp;/g' | sed 's/^/<br>/'
to preserve whitespace. You can use that without getting the font changing effect that <pre>induces.

HTML Table Format

$ printf "<pre>%s</pre>\n" "$storage" >> file.html
There should be no need to include column. This is a candidate for a HTML table, and could be begotten by something like:df -PTh | \
sed '1d' | \ sort -n -k6 | \ awk ' { printf "\n\t<tr>"; for (n = 1; n < 7; ++n) printf("\n\t<td>%s</td>",$n); printf "\n\t<td>"; for(;n <= NF; ++n) printf("%s ",$n); printf "</td>\n\t</tr>" } '
Wrap it in something like:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Disk space usage</title>
<style>
table, td, th {
  border : 1px solid green;
}
th {
  background-color: green;
  color : white;
}
</style>
</head><body>
<table>
  <tr>
    <th>Filesystem</th>
    <th>Type</th>
    <th>Size</th>
    <th>Used</th>
    <th>Avail</th>
    <th>Use%</th>
    <th>Mounted on</th>
  </tr>
  <!-- df output awk table -->
  <?php include('file.html'); ?>
</table>
</body>
</html>