我想要一个生成 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/