7

I am writing a very simple bash script that asks questions that include text from previous answers. For example:

questionText="Hi $userName, I'm going to ask you some questions. At the end of the process, I'll output a file that might be helpful to you."
echo "$questionText"

Some of these questions are quite long. The output from echo soft-wraps in my macOS Terminal window, but by character rather than by word. How do I hard-wrap the output to a specific width in characters, by word?

I can't manually add the breaks to $questionText because the included variables could be any length.

My searches all lead me to fmt and fold, but those want text files as input, not variables.

What I'm looking for is something like echo, but with an option to word wrap the output to a specified width.

1 Answer 1

16

My searches all lead me to fmt and fold, but those want text files as input, not variables.

Just use a pipe:

printf '%s\n' "$questionText" | fold

Using the -s option will make fold only wrap on white space characters, and not in the middle of a word:

printf '%s\n' "$questionText" | fold -s
2
  • Thanks! So much better than my workaround of using a tmp.txt file. Commented Dec 3, 2016 at 0:14
  • 2
    Furthermore note that you can use a here string: fold <<< "${questionText}"
    – hek2mgl
    Commented Jan 5, 2018 at 13:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.