7

I want to display a welcome message in the start of my script:

echo "Running $0 $@"

But $@ might be very long. How can I break this line into multiple up-to-80 character lines?

1
  • BTW, you should use $@ only as "$@". For other use cases, use$*. The explanation is in the bash manage. So in your case, echo "blah $*".
    – jrw32982
    Mar 25, 2022 at 4:56

3 Answers 3

16

Use fold.

echo "Running $0 $@" | fold -sw 80

-s wraps on spaces. -w 80 sets width to 80 columns.

1
  • 4
    Note that 80 is the default value for width so w 80 can be left out (but it doesn't hurt to be specific of course).
    – Marijn
    Mar 23, 2022 at 6:46
3

Of course fold is the best option, but you can also achieve this with grep or sed:

echo "Running $0 $@" | grep -o '.\{80\}[^ ]* '
#or
echo "Running $0 $@" | sed -E 's/(.{80}[^ ]*) /\1\n/g'

Note, this will break at 80 chars + 1 word, so it might not be suitable for you.

3

Although others mentioned tools that break the lines just before the word that hits the 80-character limit, there is also another tool that tries to not break the lines just before end of after start of a sentence and does other things for better readability. Its usage is similar:

echo "…" | fmt -w 80

The -w option specifies the maximum width of the text, but the text will use only 93 percent of the line (this can be overridden by using -g).

This is how fold formats the text:

Although others mentioned tools that break the lines just before the word that 
hits the 80-character limit, there is also another tool that tries to not break 
the lines just before end of after start of a sentence and does other things 
for better readability. Its usage is similar:

    echo "…" | fmt -w 80

The `-w` option specifies the maximum width of the text, but the text will use 
only 93 percent of the line (this can be overridden by using `-g`).

The long sentence that hits the 80 character column count is this one and here.

And this is output from fmt:

Although others mentioned tools that break the lines just before the word
that hits the 80-character limit, there is also another tool that tries
to not break the lines just before end of after start of a sentence and
does other things for better readability. Its usage is similar:

    echo "…" | fmt -w 80

The `-w` option specifies the maximum width of the text, but the text will
use only 93 percent of the line (this can be overridden by using `-g`).

The long sentence that hits the 80 character column count is this one
and here.

You can notice that the last (exactly 80-char long) get wrapped, but not at column 75 (the 93 % of 80), but a word before it, because we do not want to have one word on the line alone (in printed text etc.).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .