Linux new line bash

How can I have a newline in a string in sh?

What should I do to have a newline in a string? Note: This question is not about echo. I’m aware of echo -e , but I’m looking for a solution that allows passing a string (which includes a newline) as an argument to other commands that do not have a similar option to interpret \n ‘s as newlines.

13 Answers 13

If you’re using Bash, you can use backslash-escapes inside of a specially-quoted $’string’ . For example, adding \n :

STR=$'Hello\nWorld' echo "$STR" # quotes are required here! 

If you’re using pretty much any other shell, just insert the newline as-is in the string:

Bash recognizes a number of other backslash escape sequences in the $» string. Here is an excerpt from the Bash manual page:

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded as follows: \a alert (bell) \b backspace \e \E an escape character \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \\ backslash \' single quote \" double quote \nnn the eight-bit character whose value is the octal value nnn (one to three digits) \xHH the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) \cx a control-x character The expanded result is single-quoted, as if the dollar sign had not been present. A double-quoted string preceded by a dollar sign ($"string") will cause the string to be translated according to the current locale. If the current locale is C or POSIX, the dollar sign is ignored. If the string is translated and replaced, the replacement is double-quoted. 

Источник

How to echo a New Line in Bash Shell Scripts

Learn various ways of displaying a new line in the output of echo command in Linux.

Читайте также:  Samsung scx 3205 driver linux

The echo command automatically adds a new line at the end. That’s cool.

But what if you want to display just an empty new line? Or if you want to output something that contains a new line?

The good news is that, echo lets you use the newline character \n to print a new line within the same output line if you use the -e option:

echo -e "Name\nAddress\nPhone Number"

If you run the above command, you’ll get this output:

Name Address Phone Number

That’s nice, right? Let’s have a more detailed look into it.

Display new line with -e flag of echo command (recommended)

A newline is a term we use to specify that the current line has ended and the text will continue from the line below the current one. In most UNIX-like systems, \n is used to specify a newline. It is referred to as newline character.

The echo command, by default, disables the interpretation of backslash escapes. So if you try to display a newline using the ‘\n’ escape sequence, you will notice a problem.

$ echo Hello\nworld Hellonworld $ echo 'Hello\nworld' Hello\nworld

Enclosing text in single quotes as a string literal does not work either.

That was not an expected output. To actually print a new-line, you can use the ‘-e’ flag to tell the echo command that you want to enable the interpretation of backslash escapes.

$ echo -e 'Hello\nworld' Hello world

Nice, that’s what you are looking for.

Let me some other ways to display the newline character.

echo a variable containing new line

You can store a string in a bash variable and then echo it using the ‘-e’ flag.

$ str="Hello\nworld" $ echo -e $str Hello world

Use the ‘$’ character instead of -e flag

The dollar symbol, ‘$’ is called the «expansion» character in bash. This is the character that I used in the earlier example to refer to a variable’s value in shell.

If you look closely at the snippet below, you will realize that the expansion character, in this case, acts to hold a temporary value.

$ echo Hello$'\n'world Hello world

Or, you can use the whole string as a ‘temporary variable’:

$ echo $'Hello\nworld' Hello world

I would prefer to use the -e flag, though.

echo your echo to print something with new line

When you echo a piece of text, the echo command will automatically add a newline (and here is how you can prevent it) to the end of your text.

Читайте также:  Linux distributions for old pc

This means that you can chain multiple echo commands together to cause a newline.

$ echo Hello; echo world Hello world

Use printf to print newline in Bash shell

printf is another command line tool that essentially prints text to the terminal, but it also allows you to format your text.

The usage is very simple and similar to echo but a bit more reliable and consistent.

$ printf 'Hello\nworld\n' Hello world

As expected, you have a newline without using any flags.

Conclusion

Personally, I would prefer sticking with the -e flag or go for the printf command for displaying the new lines in output. I recommend you to do the same but feel free to experiment.

Источник

How to add new lines when using echo

I didn’t know about printf, with printf it works 😛 . so what does it make not working with echo then?

There are many different implementations of echo command incompatible with each other. Thus it is recommended to use more standard tool as printf . See unix.stackexchange.com/questions/65803/… for extended overview of the problem.

9 Answers 9

Pass the -e flag to echo to make it parse escaped characters such as «\r\n», like so:

echo -e "Line 1\r\nLine2" >> readme.txt 

A nice simple «-e» option to get escape sequences working — it says on another answer that echo is unreliable and doesn’t follow standards unlike printf .

echo

An echo implementation which strictly conforms to the Single Unix Specification will add newlines if you do:

But that is not a reliable behavior. In fact, there really isn’t any standard behavior which you can expect of echo .

OPERANDS

string

A string to be written to standard output. If the first operand is -n , or if any of the operands contain a character, the results are implementation-defined.

On XSI-conformant systems, if the first operand is -n , it shall be treated as a string, not an option. The following character sequences shall be recognized on XSI-conformant systems within any of the arguments:

\a — Write an .

\b — Write a .

\c — Suppress the that otherwise follows the final argument in the output. All characters following the \c in the arguments shall be ignored.

\f — Write a .

\n — Write a .

\r — Write a .

\t — Write a .

\v — Write a .

\\ — Write a character.

\0num — Write an 8-bit value that is the zero, one, two, or three-digit octal number num .

And so there really isn’t any general way to know how to write a newline with echo , except that you can generally rely on just doing echo to do so.

A bash shell typically does not conform to the specification, and handles the -n and other options, but even that is uncertain. You can do:

shopt -s xpg_echo echo hey\\nthere 

And not even that is necessary if bash has been built with the build-time option.

—enable-xpg-echo-default

Make the echo builtin expand backslash-escaped characters by default, without requiring the -e option. This sets the default value of the xpg_echo shell option to on , which makes the Bash echo behave more like the version specified in the Single Unix Specification, version 3. See Bash Builtins, for a description of the escape sequences that echo recognizes.

printf

On the other hand, printf ‘s behavior is pretty tame in comparison.

RATIONALE

The printf utility was added to provide functionality that has historically been provided by echo . However, due to irreconcilable differences in the various versions of echo extant, the version has few special features, leaving those to this new printf utility, which is based on one in the Ninth Edition system.

The EXTENDED DESCRIPTION section almost exactly matches the printf() function in the ISO C standard, although it is described in terms of the file format notation in XBD File Format Notation.

It handles format strings which describe its arguments — which can be any number of things, but for strings are pretty much either %b yte strings or literal %s trings. Other than the %f ormats in the first argument, it behaves most like a %b yte string argument, except that it doesn’t handle the \c escape.

echo() printf

You might write your own standards conformant echo like.

. which should pretty much always do the right thing automatically.

Actually, no. That prints a literal \n at the tail of the arguments if the last argument ends in an odd number of .

echo() case $ in (\ *) printf %b\\n "$*";; (*) IFS=\ $IFS printf %b\\n "$*" IFS=$ esac 

Источник

Оцените статью
Adblock
detector