Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I echo a string with hard line wrap?

Tags:

bash

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.

like image 709
Stu Maschwitz Avatar asked Dec 14 '22 02:12

Stu Maschwitz


1 Answers

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
like image 104
Andreas Louv Avatar answered Dec 28 '22 11:12

Andreas Louv