>_ IzzyLab

Hands-on task

This task is step 9 of the course “Bash: expansions, arrays and quoting”

A config via heredoc

medium~7 min

Write /root/gen.sh that, using a heredoc, writes a multi-line config into /root/config.ini: a [server] section, and under it the lines host=localhost and port=8080. Run the script. The script is easiest to write in the Editor tab above the terminal.

What you'll practise:
  • heredoc
  • multi-line output
  • cat to a file
  • escaping substitutions
  • chmod

Topic breakdown

A heredoc is a way to feed a command a whole multi-line block of text straight from the script, without a chain of echos: after command <<MARKER come the lines as-is, and the block is terminated by the same marker at the start of its own line. The marker name is arbitrary; all that matters is that the opening and closing ones match. Quotes around the opening marker (<<'EOF') disable substitution — $, variables and special characters land in the file literally, which is exactly what's needed for a static config. The subtlety of this task is a heredoc inside a heredoc: the outer one writes the script itself, the inner one, already inside it, forms the config, so the markers are chosen to be different.

What's checked

  1. /root/config.ini is created
  2. gen.sh creates config.ini with the required lines
  3. gen.sh uses a heredoc

What it looks like