Skip to content

Instantly share code, notes, and snippets.

@Jeff-Russ
Last active June 16, 2024 04:53
Show Gist options
  • Save Jeff-Russ/80dba5aa95e1bf5c682713731098b917 to your computer and use it in GitHub Desktop.
Save Jeff-Russ/80dba5aa95e1bf5c682713731098b917 to your computer and use it in GitHub Desktop.
The best way to create a multiline document template (shell)

Demo: String Templates in Bash

The best way to create a multiline string template variable which has variables within it and contains double quotes.

IMPORTANT: The variable inserts must be assigned before the string template is declared and before it's used! EACH TIME THE INSERTS ARE MODIFIED, THE TEMPLATE MUST BE RE-RECLARED! For this reason it's sometimes handy to put the template def inside a function so you can call/re-call it before using it.

#!/bin/sh
# doc_template.sh
# the best way to create a multiline string template variable which has
# variables within it and double quotes is seen here with PACKAGE_JSON.
# This can then be printed out or written to a file as you can see on the
# bottom of this page.
# IMPORTANT: The variable inserts must be assigned before the string template
# is declared and before it's used! EACH TIME THE INSERTS ARE MODIFIED, THE
# TEMPLATE MUST BE RE-RECLARED! For this reason it's sometimes handy to put
# the template def inside a function so you can call/re-call it before using it.
PROJ="proj name"
DESC="description ..."
OWNER="author name"
NAME="contributor name"
EMAIL="[email protected]"
URL="http://www.somecrap.com"
PACKAGE_JSON=$(cat <<EOF
{
"name": "$PROJ",
"version": "0.0.1",
"description": "$DESC",
"author": "$OWNER <$EMAIL>",
"contributors": [{
"name": "$NAME",
"email": "$EMAIL"
}],
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "$URL"
},
"private": "true",
"license": "MIT"
}
EOF
)
# must use doublequotes!
printf "$PACKAGE_JSON"
# must use doublequotes here too!
printf "$PACKAGE_JSON" > newfile.txt
@rewired-gh
Copy link

Thanks a lot. This is the definite answer. All the answers on StackOverflow and StackExchange are over-complicated bullshit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment