Linux echo with new lines

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

produces as output

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, the solution is to use $’string’ , for example:

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

Bash is pretty nice. It accepts more than just \n in the $» string. Here is an excerpt from the Bash manual page:

Echo is so nineties and so fraught with perils that its use should result in core dumps no less than 4GB. Seriously, echo’s problems were the reason why the Unix Standardization process finally invented the printf utility, doing away with all the problems.

So to get a newline in a string, there are two ways:

There! No SYSV vs BSD echo madness, everything gets neatly printed and fully portable support for C escape sequences. Everybody please use printf now for all your output needs and never look back.

What I did based on the other answers was

I find the -e flag elegant and straight forward

If the string is the output of another command, I just use quotes

The problem isn’t with the shell. The problem is actually with the echo command itself, and the lack of double quotes around the variable interpolation. You can try using echo -e but that isn’t supported on all platforms, and one of the reasons printf is now recommended for portability.

You can also try and insert the newline directly into your shell script (if a script is what you’re writing) so it looks like.

The only simple alternative is to actually type a new line in the variable:

Yes, that means writing Enter where needed in the code.

There are several equivalents to a new line character.

But all those require «an interpretation» by some tool (POSIX printf):

And therefore, the tool is required to build a string with a new-line:

In some shells, the sequence $ ‘ is an special shell expansion. Known to work in ksh93, bash and zsh:

Of course, more complex solutions are also possible:

A $ right before single quotation marks ‘. \n. ‘ as follows, however double quotation marks doesn’t work.

I’m no bash expert, but this one worked for me:

I found this easier to formatting the texts.

Disclaimer: I first wrote this and then stumbled upon this question. I thought this solution wasn’t yet posted, and saw that tlwhitec did post a similar answer. Still I’m posting this because I hope it’s a useful and thorough explanation.

Читайте также:  Лучший дистрибутив линукс для работы

Short answer:

This seems quite a portable solution, as it works on quite some shells (see comment).
This way you can get a real newline into a variable.

The benefit of this solution is that you don’t have to use newlines in your source code, so you can indent your code any way you want, and the solution still works. This makes it robust. It’s also portable.

Longer answer:

Explanation of the above solution:

The newline would normally lost due to command substitution, but to prevent that, we add a ‘q’ and remove it afterwards. (The reason for the double quotes is explained further below.)

We can prove that the variable contains an actual newline character (0x0A):

(Note that the ‘%s’ was needed, otherwise printf will translate a literal ‘\n’ string into an actual 0x0A character, meaning we would prove nothing.)

Of course, instead of the solution proposed in this answer, one could use this as well (but. ):

. but that’s less robust and can be easily damaged by accidentally indenting the code, or by forgetting to dedent it afterwards, which makes it inconvenient to use in (indented) functions, whereas the earlier solution is robust.

Now, as for the double quotes:
The reason for the double quotes » surrounding the command substitution as in nl=»$(printf ‘\nq’)» is that you can then even prefix the variable assignment with the local keyword or builtin (such as in functions), and it will still work on all shells, whereas otherwise the dash shell would have trouble, in the sense that dash would otherwise lose the ‘q’ and you’d end up with an empty ‘nl’ variable (again, due to command substitution).
That issue is better illustrated with another example:

Источник

How to Get a New Line in Shell Script

Newline is used to identify the end of a line in a script to mark the beginning of a new line, referred to as line break or line feed. Just as you will put the br tag in HTML scripts to force the subsequent characters into a new line, that’s what newline means in shell scripts.

Here you will find out:

  • how to skip from one line to another
  • different methods of how to use a new line
  • when DiskInternals can help you

Are you ready? Let’s read!

The simplest way to use a new line in a shell script

There are quite a couple of ways to insert a new line in a shell script. However, here are some of the simplest methods to do this:

The script above will print

When you write the “echo” command without attaching any argument, it prints a blank line.

Here’s another way to do this:

This will print:

The most used newline character

If you don’t want to use echo repeatedly to create new lines in your shell script, then you can use the \n character. The \n is a newline character for Unix-based systems; it helps to push the commands that come after it onto a new line. An example is below.

Using printf command in a shell script

It is possible to use printf in place of echo. Printf is the alternative way to insert newlines in shell scripts instead of using echo –e. This is because the -e flag isn’t compatible with all systems.

Printf is compatible with quite many systems, and it is more reliable; however, it is not in compliance with POSIX. Also, you will need to add \n at the end, because printf doesn’t automatically add new lines as echo does.

What to do to open Linux files from Windows?

Typically, you cannot open Linux files from Windows, but sometimes you may be in urgent need to access the files in your Ext2/3/4 partitions. In such scenarios, DiskInternals Linux Reader can be of great help. This software tool helps you to access Linux files from a Windows PC. It is a freeware program with an intuitive interface. Using DiskInternals Linux Reader, you can view and access Linux files, but you cannot edit them directly.

Steps to read Linux files on Windows

First, you need to install DiskInternals Linux Reader on your PC.

Launch the app to view all the Linux partitions files.

Choose the partition where you saved the Linux files.

View all the Linux files; Linux Reader can read media files, documents, and any other files on the file systems (Ext2/3/4, ReiserFS, Reiser4, HFS, HFS+, FAT, exFAT, NTFS, ReFS). To view a file, right-click on the file and select “Preview in New Window”.

Now copy the files from the Linux partition to Windows partitions and start editing.

Источник

Trying to embed newline in a variable in bash [duplicate]

I want last echo to print

Notice that I want the variable p to contain newlines. How do I do that?

7 Answers 7

Summary

Inserting a new line in the source code

Using $’\n’ (only bash and zsh)

Details

1. Inserting \n

echo -e interprets the two characters «\n» as a new line.

Avoid extra leading newline

Using a function

2. Inserting a new line in the source code

Avoid extra leading newline

Using a function

3. Using $’\n’ (less portable)

bash and zsh interprets $’\n’ as a new line.

Avoid extra leading newline

Using a function

Output is the same for all

Special thanks to contributors of this answer: kevinf, Gordon Davisson, l0b0, Dolda2000 and tripleee.

  • See also BinaryZebra’s answer providing many details.
  • Abhijeet Rastogi’s answer and Dimitry’s answer explain how to avoid the for loop in above bash snippets.

The trivial solution is to put those newlines where you want them.

Yes, that’s an assignment wrapped over multiple lines.

However, you will need to double-quote the value when interpolating it, otherwise the shell will split it on whitespace, effectively turning each newline into a single space (and also expand any wildcards).

Generally, you should double-quote all variable interpolations unless you specifically desire the behavior described above.

If you want to store it in a variable and then use it with the newlines intact, you will have to quote your usage correctly:

Or, to fix your example program literally:

There are three levels at which a newline could be inserted in a variable.
Well . technically four, but the first two are just two ways to write the newline in code.

1.1. At creation.

The most basic is to create the variable with the newlines already.
We write the variable value in code with the newlines already inserted.

Or, inside an script code:

Yes, that means writing Enter where needed in the code.

1.2. Create using shell quoting.

The sequence $ ‘ is an special shell expansion in bash and zsh.

The line is parsed by the shell and expanded to « var=»a newline b newline c» », which is exactly what we want the variable var to be.
That will not work on older shells.

2. Using shell expansions.

It is basically a command expansion with several commands:

The bash and zsh printf ‘%b’

The bash printf -v

Plain simple printf (works on most shells):

3. Using shell execution.

All the commands listed in the second option could be used to expand the value of a var, if that var contains special characters.
So, all we need to do is get those values inside the var and execute some command to show:

Note that printf is somewhat unsafe if var value is controlled by an attacker.

Источник

How to put a newline special character into a file using the echo command and redirection operator?

I would like to create a file by using the echo command and the redirection operator, the file should be made of a few lines.

I tried to include a newline by «\n» inside the string:

but this way no file with three lines is created but a file with only one line and the verbatim content of the string.

How can I create using only this command a file with several lines ?

5 Answers 5

You asked for using some syntax with the echo command:

(But consider also the other answer you got.)

The $’. ‘ construct expands embedded ANSI escape sequences.

What echo does with character escapes is implementation defined. In many implementations of echo (including most modern ones), the string passed is not examined for escapes at all by default.

With the echo provided by GNU bash (as a builtin), and some other echo variants, you can do something like the following:

However, it really sounds like you want printf , which is more legible to my eye, and more portable too (it has this feature defined by POSIX):

You also might consider using a here document:

Here are some other ways to create a multi-line file using the echo command:

where the second and third commands use the >> redirection operator, which causes the output of the command to be appended (added) to the file (which should already exist, by this point).

where the parentheses group the echo commands into one sub-process, which looks and acts like any single program that outputs multiple lines (like ls , for example).

A subtle variation on the above is

This is slightly more efficient than the second answer in that it doesn’t create a sub-process. However, the syntax is slightly trickier: note that you must have a space after the < and a semicolon before the >.

Источник

«echo -n» prints «-n»

I have a problem with echo in my script:

and moves to the next line. In the console it’s working correcly without newline:

11 Answers 11

There are multiple versions of the echo command, with different behaviors. Apparently the shell used for your script uses a version that doesn’t recognize -n .

The printf command has much more consistent behavior. echo is fine for simple things like echo hello , but I suggest using printf for anything more complicated.

What system are you on, and what shell does your script use?

bash has a «built-in» command called «echo»:

Additionally, there is an «echo» command that is a proper executable (that is, the shell forks and execs /bin/echo , as opposed to interpreting echo and executing it):

The behavior of either echo ‘s WRT to \c and -n varies. Your best bet is to use printf , which is available on four different *NIX flavors that I looked at:

It works for me as expected (as I understood from your question).

Note that I got this information from the man page. The man page also notes the shell may have its own version of echo , and I am not sure if bash has its own version.

To achieve this there are basically two methods which I frequently use:

1. Using the cursor escape character ( \c ) with echo -e

  • -e flag enables the Escape characters in the string.
  • \c brings the Cursor back to the current line.

2. Using the printf command

Источник

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