#!/usr/bin/env bash fold() { shopt -s checkwinsize ( : : ) width="${1:-$COLUMNS}" while read -r line; do : "${line// / }" IFS=$'\n' read -d "" -ra words <<<"${line// /$'\n'}" ll=0 for word in "${words[@]}"; do wl="${#word}" if ((ll + wl > width)); then printf '\n' else ((ll += wl)) printf '%s ' "$word" fi done done } fold "$@"