How to make newline for bash output on CGI/bash

I would like to display the results of Linux commands on the web

When operating a Linux server, I routinely type commands from the terminal, but I’ve come to think that it would be easier if I could check the status from the web.

It would be easier to operate if you could write a script for repetitive setting changes and execute it from the web, instead of just entering a command and checking the status.

Display dynamic web pages using CGI

It is not possible to display dynamic content such as command results simply by writing a web page using HTML.
This time, we will display the results of Linux commands with CGI using bash.

Put file to /var/www/cgi-bin/

/var/www/cgi-bin/ is CGI-enabled by default.
Setting is necessary when running CGI in another folder.

echo “Content-type: text/html”
echo “”
echo “Hello World!”

Put file as /var/www/cgi-bin/test.cgi
Hello World! is displayed.

Use bash command


echo “Content-type: text/html”
echo “”
echo “Hello World!”
echo “<br>”

make newline with echo “<br>”
The date command displays the server time.

Use commands with multiple lines of output

I wanted to display a list of logged-in users with who or w, but if I used the command normally, even if there were multiple users, the result would be displayed in one line, so I was in trouble.
The same is true when displaying the state of a network interface, such as ifconfig eth0.

The result of ifconfig eth0 is printed in one line.

There are newlines.


echo “Content-type: text/html”
echo “”

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

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

while read line
echo $line
echo “<br>”
done < /var/www/html/ifcofigeth0

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.


It’s convenient to bring your shell scripting knowledge to the web.
I think that it is possible to change the display contents using conditional expressions, use radio buttons, and so on.
There is also a tool called Webmin that allows you to view/set various Linux settings from a GUI, but I think you can learn to create your own pages with CGI.

This time, we are executing commands to the server running Apache, but you can also use SSH remote commands to display information on other hosts.


TwitterFacebookLinkedInHatenaPocketCopy Link
Copied title and URL