Code formatting guides

Check a shell formatter output with a quoted here-document

·

Choose the shell first when you reformat a script. The built-in Bash and POSIX sh examples share a quoted here-document, but only Bash mode can parse the array in the Bash example.

Bash Formatter

Format the Bash example with two spaces

Choose Bash, choose 2 spaces, load the example and select Format shell. The labels assignment becomes a compact array, a space appears before do, and the printf line is indented by two spaces.

Look at the three lines below the loop. The quoted NOTE delimiter makes the body literal. Its first two spaces and the characters $label must stay in the output.

The formatted here-document body and delimiter
cat << 'NOTE'
  $label stays literal in this note.
NOTE

GNU Bash Manual on here-documentsmvdan shell parser and formatter

Compare the same job in POSIX sh

Switch Shell dialect to POSIX sh and try to format the existing Bash sample. Expect a parser error on the array assignment. Select Load example again to get the POSIX version, where the loop lists both quoted labels directly.

Format the POSIX sample and switch Indentation to Tabs. The loop's printf line changes indentation. The spaces inside the quoted here-document stay literal.

POSIX shell command language

Check the downloaded shell file

Download formatted.sh. Use the syntax-check option for the intended shell, such as bash -n formatted.sh for Bash or dash -n formatted.sh for the POSIX sample. A successful parse checks shell grammar. Compare string and here-document bytes as a separate check.

GNU Bash Manual on here-documentsPOSIX shell command language

Common questions

Is a quoted here-document the same as an unquoted one?

Quoting any part of the delimiter prevents parameter, command and arithmetic expansion in the body. Check the delimiter as well as the content.

What should I do when a formatter flags the end of a line?

Check the surrounding construct for the missing terminator. For a here-document, verify the closing spelling and its indentation against the opening operator.

Sources

Put it into practice.

Related guides