Bash Script to Generate HTML Report with Example
echo commands to write HTML tags into a file, for example: echo "Report
" > report.html generates a basic HTML report.Examples
How to Think About It
echo to write the opening tags, add content lines dynamically, then close with the ending tags. This way, you build the report step-by-step.Algorithm
Code
#!/bin/bash output_file="report.html" # Start HTML cat <<EOF > "$output_file" <html> <head><title>Sample Report</title></head> <body> <h1>Report</h1> EOF # Add content items=("Item 1" "Item 2" "Item 3") if [ ${#items[@]} -eq 0 ]; then echo "<p>No items found.</p>" >> "$output_file" else echo "<ul>" >> "$output_file" for item in "${items[@]}"; do echo " <li>$item</li>" >> "$output_file" done echo "</ul>" >> "$output_file" fi # End HTML cat <<EOF >> "$output_file" </body> </html> EOF # Print output file path echo "HTML report generated: $output_file"
Dry Run
Let's trace the script generating a report with three items.
Create HTML header
Writes ,
, , andReport
to report.htmlAdd list items
Loops over items array and writes
- tags
Close HTML tags
Writes and to complete the file
| Step | Action | Content Written |
|---|---|---|
| 1 | Write header | , , , Report |
| 2 | Write list items |
|
| 3 | Write footer |
Why This Works
Step 1: Start HTML structure
The script uses cat <
Step 2: Add dynamic content
It checks if the items array is empty; if not, it loops through each item and appends it as a list item inside <ul> tags.
Step 3: Close HTML tags
Finally, it appends the closing </body> and </html> tags to complete the HTML document.
Alternative Approaches
#!/bin/bash output_file="report.html" printf '<html><body><h1>Report</h1><ul>' > "$output_file" items=("Item A" "Item B") for item in "${items[@]}"; do printf '<li>%s</li>' "$item" >> "$output_file" done printf '</ul></body></html>' >> "$output_file" echo "HTML report generated: $output_file"
#!/bin/bash output_file="report.html" items=("One" "Two") cat > "$output_file" <<EOF <html> <body> <h1>Report</h1> <ul> $(for i in "${items[@]}"; do echo " <li>$i</li>"; done) </ul> </body> </html> EOF echo "HTML report generated: $output_file"
Complexity: O(n) time, O(n) space
Time Complexity
The script loops through each item once to add it to the report, so time grows linearly with the number of items.
Space Complexity
The script stores the items in an array and writes output directly to a file, so space grows linearly with input size.
Which Approach is Fastest?
Using printf or embedding loops in here documents can be faster and cleaner than multiple echo calls.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Echo with append | O(n) | O(n) | Simple scripts, beginners |
| Printf formatting | O(n) | O(n) | Better formatting control |
| Here document with embedded loop | O(n) | O(n) | Cleaner code, moderate complexity |