I ran into fold while trying to format some plain-text output for a fixed-width terminal that a legacy monitoring system expected — 80 columns, no exceptions, or the display would render garbled. Rather than manually inserting line breaks, fold did the whole job in one command. It’s a small, unglamorous utility, but any time text needs to be reflowed to a specific width for a terminal, a printer, or a fixed-format system, it’s exactly the right tool.
What fold Does
fold wraps each line of input so that it doesn’t exceed a specified width, breaking long lines into multiple shorter lines.
fold [OPTION]... [FILE]...
I tested the default behavior, which wraps at 80 columns:
$ echo "This is a long line that should be wrapped at a certain width for testing purposes today" | fold
This is a long line that should be wrapped at a certain width for testing purpos
es today
The line was broken at exactly the 80th character, mid-word, with no regard for word boundaries — that’s the default, unconditional wrapping behavior.
Core Options and Parameters
-w WIDTH — Set the Wrap Width
$ echo "This is a long line that should be wrapped at a certain width for testing" | fold -w 20
This is a long line
that should be wrapp
ed at a certain widt
h for testing
I tested this and confirmed each output line is exactly 20 characters wide, breaking mid-word wherever the count lands — useful when you need strict, predictable line lengths regardless of readability at the break points.
-s — Break at Spaces (Word-Aware Wrapping)
The default hard-wrap behavior can split words in half, which is often not what you want for readable text output. -s tells fold to break at the last whitespace before the width limit instead:
$ echo "This is a long line that should be wrapped at word boundaries for testing" | fold -s -w 20
This is a long line
that should be
wrapped at word
boundaries for
testing
I tested this directly and confirmed the difference from plain -w: instead of cutting wrapp|ed mid-word, -s breaks cleanly after be and before wrapped, keeping every word intact — the output reads naturally rather than looking mechanically chopped.
-b — Count Bytes Instead of Columns
By default, fold counts display columns (accounting for tab expansion and similar considerations). -b switches to counting raw bytes instead, which matters primarily when working with multibyte text encodings (like UTF-8) where a single visible character can occupy more than one byte:
fold -b -w 40 file.txt
I tested fold against text containing accented characters (Héllo Wörld...) and observed that wrapping behavior with multibyte characters can produce visually uneven line lengths depending on locale and encoding handling — this is a genuine area where care is warranted. If you’re working with non-ASCII text and need precise wrapping, test carefully against your actual data and locale settings, since column-counting versus byte-counting behavior can differ from what you might intuitively expect.
How fold Works Internally
fold reads input character by character (or byte by byte with -b), maintaining a running count of the current line’s width. Once the count reaches the specified width (default 80), it inserts a newline and resets the counter, continuing until the next natural newline in the original input is reached — at which point the counter resets for the next input line. With -s, instead of breaking exactly at the width limit, fold looks backward from that point for the most recent whitespace character and breaks there instead, effectively “rewinding” slightly to avoid splitting a word — this is why -s output lines are typically slightly shorter than the specified width rather than exactly matching it.
Practical, Real-World Examples
1. Formatting Text for an 80-Column Terminal or Printout
fold -s -w 80 essay.txt
2. Wrapping Long Lines in a Log File for Readability
fold -w 100 -s wide_log.txt | less
Some log lines (particularly stack traces or JSON blobs) can run for hundreds of characters; wrapping them to a manageable width before viewing makes them dramatically easier to read in a normal terminal window.
3. Preparing Text for Fixed-Width Legacy Systems
fold -w 72 message.txt > formatted_message.txt
Certain older protocols and formats (some email conventions, fixed-width mainframe-style reports, certain embedded display systems) genuinely require strict line-width limits — fold handles this formatting requirement without needing a full text-processing script.
4. Combining with pr for Printable Output
fold -s -w 65 report.txt | pr --header="Monthly Report" | lpr
Wrapping text to a printer-friendly width before formatting with pr and sending to lpr produces cleanly paginated, readable printed output.
5. Wrapping Base64-Encoded Data to a Standard Width
base64 file.bin | fold -w 76
Many standards (like MIME/email attachment encoding) expect base64 data wrapped at a specific width (76 characters is a very common convention); fold reformats a single long base64 string into properly wrapped lines. Note that most base64 implementations already wrap output at a default width themselves, but fold is a useful fallback when working with base64 data that was generated without wrapping.
fold in Shell Scripting and Automation
A pattern I’ve used when generating plain-text email bodies from a script, respecting traditional email line-length conventions (72–78 characters is a widely followed convention to avoid awkward wrapping in recipients’ mail clients):
#!/bin/bash
{
echo "Subject: Weekly Status Report"
echo
generate_status_summary.sh | fold -s -w 72
} | sendmail user@example.com
Another pattern: reflowing wide command output (like a df -h report with long mount point paths) for inclusion in a fixed-width terminal dashboard or alert message:
df -h | fold -w 60 -s
Comparing fold to Related Commands
| Task | Best Tool |
|---|---|
| Hard-wrapping text at a fixed width | fold |
| Paragraph-aware reflowing (merging short lines, wrapping at width) | fmt |
| Formatting for print with headers/pagination | pr |
| Truncating (not wrapping) long lines | cut -c1-N |
| Full text reformatting/justification | fmt -w or a word processor |
fold and fmt are often confused. fold treats each input line independently and simply breaks it at the width limit (with or without word-awareness via -s) — it never merges separate lines together. fmt, by contrast, is paragraph-aware: it can join short lines together and reflow whole paragraphs to a target width, which is closer to what a word processor’s “justify” or “reflow” feature does. If you just need to prevent lines from exceeding a width, fold is the simpler, more predictable tool; if you need genuine paragraph reflowing, fmt is the better fit.
Troubleshooting Common fold Issues
Words split awkwardly in the middle — this is the default, expected behavior; add -s to break at word boundaries instead.
Output line lengths look inconsistent with -s — this is also expected; since -s breaks at the nearest preceding whitespace rather than exactly at the width limit, lines using -s will typically be slightly shorter than (never longer than) the specified width, and the exact length varies depending on where whitespace naturally falls.
Wrapping looks wrong with non-ASCII text — check whether -b (byte-counting) is being used unintentionally on multibyte UTF-8 content, or verify your locale settings (LANG/LC_ALL) are consistent with the encoding of the text being processed; multibyte handling is one of the genuine rough edges of fold and deserves testing against your actual data.
Tabs cause unexpected width miscounts — fold by default treats tab characters according to standard column-counting conventions (expanding to the next tab stop), which can make the visual width differ from a naive per-character count; consider expanding tabs to spaces first with expand if precise, predictable width control matters.
Performance Considerations
fold streams input character by character and is lightweight, scaling linearly with input size; it’s rarely a performance bottleneck even on fairly large files. For extremely large files, piping through fold adds negligible overhead compared to the cost of whatever is generating or consuming the wrapped text on either side of it.
Security Implications
fold carries no meaningful direct security risk — it doesn’t interpret its input as anything beyond a character/byte stream to reformat. As with any text tool, be aware that wrapping doesn’t sanitize or redact content; sensitive data remains just as sensitive after being reflowed to a different width.
Compatibility Across Distributions
fold is part of GNU coreutils and is standard on Ubuntu, Debian, Fedora, RHEL/CentOS, Arch, and openSUSE. It’s also specified by POSIX, so BSD and macOS ship a compatible fold implementation supporting the core -w, -s, and -b options, making it broadly portable across Unix-like systems without significant behavioral differences for typical ASCII text use cases.
fold and Terminal/System Internals
Understanding why a “wrap text at N columns” utility exists at all requires a little historical context. Terminals — both the physical hardware terminals of the 1970s and 80s and the virtual terminal emulators we use today — have a fixed number of display columns, traditionally 80. Before terminal emulators could automatically soft-wrap long lines the way modern ones do, or before a document needed to be sent to a printer with fixed page-width constraints, text that exceeded the display or print width would either be truncated or would produce garbled, misaligned output. fold was written specifically to solve this class of problem: reflow arbitrary text so it never exceeds a hard width limit, regardless of what’s displaying or printing it.
Even today, this matters in more places than people expect: serial console output on embedded and networking devices, certain legacy monitoring dashboards, fixed-width mainframe interchange formats, and printed reports that need predictable pagination all still enforce strict column limits, and fold remains a perfectly good tool for meeting that requirement without writing custom logic.
Deeper Look at Column Counting vs Byte Counting
By default, fold counts display columns, not bytes and not necessarily raw characters. This distinction matters when tab characters are present, since a tab doesn’t occupy a single column — it expands to the next tab stop, commonly every 8 columns. This means a line containing tabs may wrap sooner (in terms of raw character count) than a line of the same character length using only spaces, because fold is accounting for the visual column position after tab expansion, not just counting characters one by one.
If precise, tab-independent character counting matters for your use case, a common practice is to expand tabs to spaces first:
expand -t 4 file.txt | fold -w 80 -s
This ensures tabs are converted to a fixed number of spaces before fold even sees the content, removing any ambiguity about how tabs should be counted during the wrapping pass.
Combining fold With Other Text Utilities
Building a Readable Diff-Style Report
diff -u old.txt new.txt | fold -s -w 80
Wide diff output (particularly diffs of long lines, like minified JSON or generated code) becomes far more readable once wrapped, even though the -/+ prefix characters at the start of each diff line get pushed slightly out of visual alignment across wrapped segments — a tradeoff worth knowing about if you rely on that alignment for quick visual scanning.
Wrapping Man Page Output for Non-Standard Terminal Widths
man ls | col -b | fold -s -w 60
col -b strips backspace-based formatting characters that man output sometimes includes for bold/underline rendering, and fold then reflows the plain text to a narrower width than the terminal’s actual size — useful when preparing man page content for inclusion in a narrower fixed-width document or embedded help screen.
Troubleshooting: Verifying Wrap Width Behavior
If you’re unsure whether fold is counting columns as you expect on a particular file, a quick sanity check is piping the output through awk to measure line lengths directly:
fold -w 40 file.txt | awk '{ print length, $0 }' | sort -rn | head -5
This prints the five longest resulting lines along with their length, letting you confirm empirically that nothing exceeds your intended width — a good habit before relying on fold‘s output in a context (like a fixed-width protocol) where exceeding the limit would cause a real failure downstream.
Summary
fold does one job — enforce a maximum line width — and does it predictably. The default hard-wrap is fine for strict fixed-width requirements (base64 data, legacy fixed-format systems), while -s is what you want any time human readability matters and words shouldn’t be split mid-way. For anything requiring actual paragraph reflowing rather than simple width-capping, reach for fmt instead.
References
- GNU Coreutils Manual —
fold: https://www.gnu.org/software/coreutils/manual/html_node/fold-invocation.html - POSIX Specification for
fold: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/fold.html man fold(local manual page)
