DEV Community

Cover image for How to make newline for bash output on CGI/bash
MSugitani
MSugitani

Posted on • Updated on

How to make newline for bash output on CGI/bash

Use CGI for dynamic web site

In case of Web site that using CGI not static html we can show contents dynamically.
Like showing result of Linux command.
Put this sample to /var/www/cgi-bin/ as test.cgi

!/bin/bash
echo “Content-type: text/html”
echo “”
echo “Hello World!”
Enter fullscreen mode Exit fullscreen mode

This is same as static html.

Image description

#!/bin/bash
echo “Content-type: text/html”
echo “”
echo “Hello World!”
echo “<br>”
date
Enter fullscreen mode Exit fullscreen mode

If use date command it can showing date dynamically.

Image description

If the command produces multiple lines of output when executed

if use command ifconfig eth0

Image description
There are no newline.

How to resolve?

#!/bin/bash
echo “Content-type: text/html”
echo “”

echo “Hello World!”
echo “<br>”
date
echo “<br>”
echo “<br>”

sudo /usr/sbin/ifconfig eth0 > /var/www/html/ifcofigeth0

while read line
do
echo $line
echo “<br>”
done < /var/www/html/ifcofigeth0
Enter fullscreen mode Exit fullscreen mode

Output to file once and read the file 1 line by 1 line using while.
Using echo for output and use br for make newline.
Repeat this.

Image description
It is showing with newline.

In case of using echo command I found article on this.
it will use \n for make newline.

But It seem there are no article in case of If the command produces multiple lines of output when executed.

If you have any other good ideas please let me know.

Top comments (0)