Running a script created in Notepad (Windows) on Ubuntu

I created a Notepad file on Windows and copied it to Ubuntu. The file contains some iptables rules. After making the file executable using chmod +x and executing it, it didn't work.

However, when I created a Ubuntu (gedit) file and copied the same contents from the Notepad file, made it executable and ran it, it worked.

What should I do to make the Notepad file run on Ubuntu?


Solution 1:

Windows and Linux have different end-of-line symbols.

You can install the dos2unix utility that fixes it:

sudo apt-get install dos2unix

Run it this way:

dos2unix -n winfile.txt linuxfile.txt

There is also the unix2dos utility.

The Windows-to-Linux conversion can also be done without installing any special software by

 tr -d '\r' < winfile.txt > linuxfile.txt

Note: Input and output files must be different.

A sed version will edit the file "in place":

 sed  -i 's/\r//g' file.txt

Or write to another file:

 sed 's/\r//g' winfile.txt > linuxfile.txt

Solution 2:

On Windows, you need to change the End of Line (EOL) format in Notepad++ to UNIX:

enter image description here

That way it will work on Ubuntu too.

Solution 3:

Windows uses CR+LF for line breaks. In Linux/Unix you need LF. Therefore you have to replace CR+LF into LF in your script:

Install dos2unix

sudo apt-get install dos2unix

And correct your script via

dos2unix <your_script_file>

or via

dos2unix -n <your_script_file> <out_file>

if you need a different output file

More informations here


from man dos2unix

NAME
       dos2unix - DOS/Mac to Unix and vice versa text file format converter

SYNOPSIS
           dos2unix [options] [FILE ...] [-n INFILE OUTFILE ...]
           unix2dos [options] [FILE ...] [-n INFILE OUTFILE ...]

Solution 4:

I use cygwin on Windows.
Open the file with vi. Then enter

:set ff=unix<enter> followed by 
:wq<enter> 

will save the file with Unix end of line characters.