2

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?

3 Answers 3

2

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"
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Could I accommodate multiple arguments using this method?
@iCodeYouCodeWeAllCode: Sure, but there's lots of opportunity for confusion if you aren't careful. For instance, if you used $(somefunc "$2" "heading" "$1"), then inside the function $1 will refer to the script's second argument, and $3 will refer to its first. If this makes sense in terms of what the function does, great! But if it'd be clearer to have consistent references throughout, globals are a better way to go. You can also mix approaches based on what's clearest in each situation.
1

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

1 Comment

Change made. Ran ./template_creator.sh bootstrap. But it shows 'bootstrap' below <title></title>.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.