0

I use python on windows to generate .sh file, simply using file.open(),file.write() . But when I run this .sh on linux, it reports the following error.

/bin/bash^M: bad interpreter: No such file or directory

The content of my generated .sh file:

#!/bin/bash
export ICS_START=/rdrive/ics/itools/unx/bin/
source $ICS_START/icssetup.sh
......

I found vim recognized it as dos file. I guess if there is something wrong with the newline symbol.

In my python code, I use file.write('xxxx\n'). To my knowledge, '\n' is the newline on linux/unix and '\r\n' is on windows. I don't why there is still ^M when recognized by linux since I only write '\n'.

Any help would be appreciated.

lionel
  • 415
  • 1
  • 5
  • 14
  • Use `dos2unix filename.sh` to fix the newlines. – Barmar Oct 11 '18 at 02:08
  • Python translates `\n` to `\r\n` on WIndows unless you open the file in binary mode. – Barmar Oct 11 '18 at 02:08
  • @Barmar dos2unix is the method I am using now. I wonder if there is a method to solve it fundamentally. – lionel Oct 11 '18 at 02:32
  • In the old days when we used `FTP`, it would automatically convert newlines while transfering. Unfortunately, more modern tools like `scp` don't do this. – Barmar Oct 11 '18 at 02:33
  • Possible duplicate of [Using python to write text files with DOS line endings on linux](https://stackoverflow.com/q/2642036/608639), [How can I force Python's file.write() to use the same newline format in Windows as in Linux (“\r\n” vs. “\n”)?](https://stackoverflow.com/q/9184107/608639), [How to write Unix end of line characters in Windows using Python](https://stackoverflow.com/q/2536545/608639), [How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?](https://stackoverflow.com/q/2613800/608639), etc. – jww Oct 11 '18 at 03:08
  • Possible duplicate of [Bash script: bad interpreter](https://stackoverflow.com/questions/2841593/bash-script-bad-interpreter) – n. m. could be an AI Oct 11 '18 at 05:59

1 Answers1

2

You need to open the file in binary mode, otherwise it translates newlines to the local operating system's format. If you run the script on Windows, that means it converts \n to \r\n when writing the file.

with open("filename.sh", "wb") as file:

The b in the mode argument tells it to use binary mode.

Barmar
  • 741,623
  • 53
  • 500
  • 612