Skip to content

Bash pattern for printing an error message to stderr that is hard‐wrapped at 80 characters, while also keeping the code itself hard‐wrapped to 80 characters

John Karahalis edited this page Jun 22, 2024 · 7 revisions

I've often struggled with the following question in Bash: How do I accomplish all three of the following things at the same time?

  1. Print an error message to stderr.
  2. Ensure the error message is hard-wrapped to some width in the user's console. (In my case, I want it to be 80 characters.)
  3. Ensure the code that prints the error message is hard-wrapped to the same width.

I've run into this problem elsewhere, and I'm sure every language/framework has a different way of solving it. When you're a perfectionist like me (not always a good thing), you find strange dilemmas like this.

Yesterday, I found a solution that works well in Bash. Here's an example, inspired by the current version of npm-audit-fix-and-push:

if true; then
  >&2 cat <<'EOF'
Error: Working directory is dirty. Stash or commit any changes. Then, run this
command again.
EOF
fi

The conditional (if true) obviously isn't needed, since it does nothing useful in terms of program flow, but it's shown here as an example of what this solution looks like when it appears at some level of indentation.

In the end, the formatting of the error message in the source code is identical to its formatting on the console. Therefore, it's hard-wrapped in both places, and developers don't need to mess around with complex quoting and concatenation to do it.

Variations

Printing to stdout

To print the message to stdout, just remove the >&2 redirection on the second line.

Hard-wrap the console message to a smaller width

To hard-wrap the console message to a smaller width than the source code, use fold instead of cat. Here's an example where the source code is hard-wrapped at 80 characters and the console message is hard-wrapped at 20 characters:

if true; then
  >&2 fold --spaces --width 20 <<'EOF'
Error: Working directory is dirty. Stash or commit any changes. Then, run this
command again.
EOF
fi

Hard-wrap the console message to a larger width

To hard-wrap the console message to a larger width than the source code, you may need to use sed to remove linebreaks before folding.

Keeping the message indented in source code

To indent the message in source code (i.e., Error: Working... instead of (Error: Working...), you may need to use tr, sed, or some other solution to trim the the extra spaces that are printed.