Search code examples
bashunixpowercli

Carriage return characters inserted, copying from dos file


I have an issue where ^M characters are being inserted into a script file. I have a Bash script:

#!/bin/bash

# Do something
echo "hello world"

Using PowerCLI I copy the script file from Windows to a Ubuntu virtual machine:

Copy-VMGuestFile -Source "C:\test.sh" -Destination /tmp/test.sh -LocalToGuest -GuestUser root -GuestPassword p@ssword -VM VM001

After copying, when opening the file with vi the format shown is:

#!/bin/bash^M

^M
# Do something^M
echo "hello world"^M

Is there a way to stop ^M being added when copying the file? I can replace the characters using sed, but this is not a clean solution.


Solution

  • The control characters aren't being added by the copy, they are part of the Windows file.

    On Windows lines are terminated with both a carriage return and line feed. On Unix it's just the line feed so you are seeing the superfluous carriage return character in the file.

    Depending on your editor of choice on Windows you may be able to change the behaviour to be more Unix friendly. For example with sublime it's

    View->Line Endings->Unix

    Alternatively you can run the script through a translator before/after the copy. Which would do the same as you are doing with sed.