Remove Control-M In Your Unix Script

Another tip to document:

I was once a victim of wanting to run my shell script only to realize one of the reasons why I can’t run it is because of the presence of Control-M character all over my script!

Why is it so?

The cause of such Control-M presence is due to the fact that the script was created using Windows based Notepad or any non-Unix editor. Now, the scripts have to be uploaded using FTP or SFTP to the target Unix server.

Currently there are largely available GUI based tool to perform the FTP or SFTP. But one thing isn’t clear is when you FTP in your scripts, you have ensure that the mode is in ASCII. If you missed it out, you will end up having Control-M characters in your scripts.

Back to the business of removing the Control-M character, just type this command using your ‘vi’ editor. Follow the key strokes:

:%s/Control-v-m//g

After pressing the key strokes, you will see this in your ‘vi’ editor:

:%s/^M//g

Now you can review your script and satisfied that the Control-M character is gone.

For safety, before even editing your shell script, you can back it up first using the cp (copy) command:

cp -p original_file backup_file

This command will copy the file to your target backup_file with the same permission as your original_file.

Til next time. Au revoir.

Advertisements

6 thoughts on “Remove Control-M In Your Unix Script”

    1. Hey there… Thanks for the tip! I believed I’ve tried the dos2unix before but I can’t recall why I didn’t continue using it. Are there upgrades available? Lemme try visiting that tool again 😉

  1. You’re welcome. Was just throwing it out there in case you weren’t aware of it. Been ages since I’ve actually used it myself, but I don’t recall there being any issues with it. Either way, your tip is still good to know when you find yourself editing a file that has not been translated.

  2. Fantastic blog! Do you have any tips and hhints for aspiring writers?
    I’m hoping to start my ownn blog soon but I’m a
    little lost on everything. Would you recommend starting with a free platform like WordPress or go for a
    paid option? There are so many options out there that I’m completely confused ..
    Any ideas? Kudos!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s