Often you need to create configuration files inside a bash script such as when creating a bootstrap/setup script. It’s not very intuitive how you should should do it, and a lot of information found online is either unsafe or too complicated. Here is my preferred way of safely creating dynamic files using bash:
cat > /my/important/config.conf <<'EOF'
server {
listen __PORT__;
server_name __HOSTNAME__;
location / {
proxy_set_header Host $host;
}
}
EOF
# If you need to also set permissions
chown user:group /my/important/config.conf
chmod 600 /my/important/config.conf
sed -i \
-e "s|__PORT__|$PORT|g" \
-e "s|__HOSTNAME__|$HOSTNAME|g" \
/my/important/config.conf
The above sample combines Bash’s heredoc and sed to write a config file
with placeholder values (optional) and then replace them with values
from the script. Essentially, the heredoc begins with a limit string and
will feed lines into a command until it reaches the limit string. In the
example we feed input into cat which we redirect into a file.