Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing Unix line breaks on Windows with JRuby

I'm writing a Ruby script to generates a Unix shell script, but I'm unable to get JRuby to write Unix line breaks on Windows.

I have written a file test.rb which contains:

File.open("test.sh", 'w') do |f|
  f.write("#!/bin/sh\n")
  f.write("echo hello\n")
end

When I execute it with the command java -jar jruby-complete-1.6.5.jar test.rb then the generated file contains \r\n line breaks instead of \n line breaks.

How can I force JRuby to write a text file with Unix newlines?

like image 540
Esko Luontola Avatar asked Jan 19 '23 08:01

Esko Luontola


1 Answers

I managed to fix it by adding "b" to the parameters of File.open

File.open("test.sh", 'wb') do |f|
  f.write("#!/bin/sh\n")
  f.write("echo hello\n")
end

The documentation for the IO class says about it the following:

Mode |  Meaning
-----+--------------------------------------------------------
 "b" |  Binary file mode (may appear with
     |  any of the key letters listed above).
     |  Suppresses EOL <-> CRLF conversion on Windows. And
     |  sets external encoding to ASCII-8BIT unless explicitly
     |  specified.
-----+--------------------------------------------------------
like image 106
Esko Luontola Avatar answered Jan 28 '23 20:01

Esko Luontola