Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a line break to an output file in a shell script

I have a shell script that I am executing in Cygwin (maybe this is the problem). For this bit of code, I simply want to write the first line, and append a line break:

echo "`date` User `whoami` started the script." >> output.log echo >> output.log 

But the output.log file never seems to take the break. If I run the script multiple times, it's as if the second echo doesn't write to the file.

I've also tried:

echo -e "`date` User `whoami` started the script.\n" >> output.log 

It yields the same results.

The odd thing is if I just enter the second echo statement above on the command line, without appending to the file, it gives me the expected output with the trailing line break.

like image 351
Ode Avatar asked Mar 16 '12 16:03

Ode


People also ask

How do you add a line break in shell script?

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.

How do I append to an output file?

Append Text Using >> Operator The >> operator redirects output to a file, if the file doesn't exist, it is created but if it exists, the output will be appended at the end of the file. For example, you can use the echo command to append the text to the end of the file as shown.

How do you add a new line in output?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

Which command is used to add a newline to the end of the output?

The endl function, part of C++'s standard function library inserts a newline character into your output sequence, pushing the subsequent text to the next output line.


1 Answers

I'm betting the problem is that Cygwin is writing Unix line endings (LF) to the file, and you're opening it with a program that expects Windows line-endings (CRLF). To determine if this is the case — and for a bit of a hackish workaround — try:

echo "`date` User `whoami` started the script."$'\r' >> output.log 

(where the $'\r' at the end is an extra carriage-return; it, plus the Unix line ending, will result in a Windows line ending).

like image 87
ruakh Avatar answered Nov 09 '22 21:11

ruakh