iCodeYouCodeWeAllCode
iCodeYouCodeWeAllCode

Reputation: 55

Bash Script to generate HTML Template

I want a Bash script that generates a HTML template. The template will include libraries based on the input arguments at the command line. Here is my idea:

#!/bin/bash

function libraries
{
  if [ "$1" == "bootstrap" ]; then
      echo "<link type="text/css" rel="stylesheet" href="css/bootstrap.css" />"
  fi
}

##### Main

cat << _EOF_
  <!DOCTYPE html>
  <html>
  <head>
      <title> </title>
      $(libraries)
  </head>

  <body>

  </body>
  </html>
_EOF_

When I run ./template_creator.sh bootstrap I get this output:

<!DOCTYPE html>
  <html>
  <head>
      <title> </title>

  </head>

  <body>

  </body>
  </html>

If I don't include the if statement and just echo, it outputs fine. So I am thinking the trouble is in the if statement. Any suggestions?

Upvotes: 2

Views: 5956

Answers (3)

SLePort
SLePort

Reputation: 15461

You can use printf to inject variables in your template.

In your template use the printf formats (eg. %s) as inserting points.

This way you can even use a file for your template (calling it with tpl=$(cat "main.tpl") and handle your variables in your script.

libraries() {
  if [ "$1" == "bootstrap" ]; then
      link='<link type="text/css" rel="stylesheet" href="css/bootstrap.css" />'
      printf "$tpl" "$link"
  fi
}

##### Main

read -d '' tpl << _EOF_
  <!DOCTYPE html>
  <html>
  <head>
      <title> </title>
      %s
  </head>

  <body>

  </body>
  </html>
_EOF_

libraries "$1"

Upvotes: 2

Gordon Davisson
Gordon Davisson

Reputation: 125928

Inside a function, $1 refers to the first argument passed to that function, not the first argument passed to the script. You can either pass the script's first argument on to the function by using $(libraries "$1") in the here-document, or assign it to a global variable at the beginning of the script and then use that in the function.

Upvotes: 1

1ac0
1ac0

Reputation: 2939

Instead of $(libraries) write $(libraries) $1.

Upvotes: 1

Related Questions