Skip to content
Linux Basics: Wrap Display Lines with GNU fold

Linux Basics: Wrap Display Lines with GNU fold

October 27, 2026

An unbroken diagnostic token may be wider than a terminal. GNU fold inserts line breaks at a chosen width. Compare hard wrapping, space-aware wrapping, and byte counting with controlled ASCII input.

Prepare a scratch directory

Tested on Linux with GNU coreutils 9.7 and GNU Bash 5.2.37. You need the named runtime, Bash, a text editor, and the standard mktemp, rm, and rmdir utilities. The script creates a separate temporary fixture directory and removes only that directory on exit. It does not operate on your existing files.

Keep using the same terminal. Stop if setup fails, before saving the source:

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Run the example

Save this as demonstrate-gnu-fold.sh:

#!/usr/bin/env bash
set -euo pipefail
export LC_ALL=C
fixture_dir="$(mktemp -d)"
trap 'rm -rf -- "$fixture_dir"' EXIT
cd -- "$fixture_dir"
printf 'abcdefghijkl\n' > token.txt
printf 'Hard width four:\n'
fold -w 4 token.txt > wrapped.txt
cat wrapped.txt
test "$(wc -l < wrapped.txt)" -eq 3
printf 'Break at spaces when possible:\n'
printf 'red green blue\n' | fold -s -w 10 | cat -A
printf 'Tab counted as one byte:\n'
printf 'ab\tcd\n' | fold -b -w 4 | cat -T

Run it:

bash demonstrate-gnu-fold.sh

Observed output:

Hard width four:
abcd
efgh
ijkl
Break at spaces when possible:
red green $
blue$
Tab counted as one byte:
ab^Ic
d

Read the result

The first command breaks even a word with no spaces. -s prefers a space within the selected width; it can leave a space at the end of an output line. cat -A marks each line ending with $, making that trailing space visible. The final example selects byte counting with -b. cat -T renders the literal tab as ^I so that otherwise invisible character is visible in this article’s output.

Apply it carefully

Default width accounting treats tabs, backspaces, and carriage returns specially. Byte counting is not Unicode character counting and can split a multibyte encoding. Use this for controlled display text rather than rewriting JSON, source, or structured logs whose line boundaries carry meaning. Unlike fmt, fold does not reflow a paragraph by joining existing lines. Keep the original file separate from the wrapped output.

The official reference describes the API and its options. The checks above cover the specific fixture, not every possible input or environment.

Clean up

Remove the source and then the empty practice directory:

rm -- demonstrate-gnu-fold.sh
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

If the directory is not empty, inspect the remaining files rather than deleting unknown contents.

Acknowledgements

This post was created with assistance from AI.

Last updated on