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.
Next, we use sed to find and replace patterns in our newly created file.
The -i flag tells it to change the file in place and -e are patterns
we want to replace.
Extra
In the example, sometimes you need to set owner and permissions of a config
file, you can also do it in one command with install:
install -m 600 -o user -g group /dev/stdin /my/important/config.conf <<'EOF'
server {
listen __PORT__;
server_name __HOSTNAME__;
location / {
proxy_set_header Host $host;
}
}
EOF
sed -i \
-e "s|__PORT__|$PORT|g" \
-e "s|__HOSTNAME__|$HOSTNAME|g" \
/my/important/config.conf
The -m flag is file permission you want to set, -o is owner, and -g is the group.
This can be very useful and time saving when dealing with many complex file
permissions!
References
The following are sources to learn more about each command or topic that I think are high quality.