用于生成 HTML 模板的 Bash 脚本

标签 bash

我想要一个生成 HTML 模板的 Bash 脚本。该模板将包含基于命令行输入参数的库。这是我的想法:

#!/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_

当我运行 ./template_creator.sh bootstrap 时,我得到以下输出:

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

  </head>

  <body>

  </body>
  </html>

如果我不包含 if 语句而只是 echo,则输出正常。所以我认为问题出在 if 语句中。有什么建议么?

最佳答案

您可以使用 printf 在模板中注入(inject)变量。

在您的模板中使用 printf 格式(例如 %s)作为插入点。

这样,您甚至可以使用模板文件(使用 tpl=$(cat "main.tpl" 调用它)并在脚本中处理变量。

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"

关于用于生成 HTML 模板的 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36257117/

相关文章:

linux - 打印一种文件类型总计 'du',目录不平坦

regex - Bash 使用 cut 获取字段

string - 将回车 (\r) 转换为实际覆盖

string - 一个 ‘contract’ 字符串如何转义 Bash 中的特殊字符?

bash - 如何多次 'expect' 某事?

bash - 在 Unix 中不同时写入文件

Bash 不从函数中打印换行符?

bash - 损坏 : Elif in For loop with increment counter

linux - 如何遍历 shell 命令的输出?

bash - EC2 用户数据,启动时未执行的特定命令,手动工作正常